Converting VARCHAR to DECIMAL values in MySql
Asked Answered
G

4

9

I have imported a CSV file that contains string values (eg.eating) and floating values (eg. 0.87) into a table in my phpMyAdmin database. After I get ride of all the string values and retain only the rows that have the decimal values, I need to convert such values from VARCHAR to DECIMAL/FLOAT so that I can perform a MAX() on this attribute.

How do I do this? Each time I try doing this through the GUI in phpMyAdmin, all my values are automatically rounded off to 0 and 1s.

Please help me!

Garik answered 9/3, 2014 at 5:21 Comment(0)
F
3

I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.

ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)

for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html

And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.

Fiester answered 9/3, 2014 at 5:29 Comment(0)
B
9

Without Converting you can find Maximum using this query

select max(cast(stuff as decimal(5,2))) as mySum from test;

check this SQLfiddle

your demo table:

create table test (
   name varchar(15),
   stuff varchar(10)
);

insert into test (name, stuff) values ('one','32.43');
insert into test (name, stuff) values ('two','43.33');
insert into test (name, stuff) values ('three','23.22');

Your Query:

For SQL Server, you can use:

select max(cast(stuff as decimal(5,2))) as mySum from test;
Broadcasting answered 9/3, 2014 at 5:32 Comment(0)
K
4

Be aware that if you convert from VARCHAR to DECIMAL and do not specify a precicision and maximum number of digits (i.e. DECIMAL instead of DECIMAL(5,2)) MySQL will automatically round your decimals to integer values.

Kiva answered 23/6, 2014 at 20:7 Comment(0)
F
3

I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.

ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)

for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html

And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.

Fiester answered 9/3, 2014 at 5:29 Comment(0)
T
0

Hope it may help someone

select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1
Telemetry answered 18/11, 2020 at 22:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.