I have a table containing latitude and longitude values stored as strings (VARCHAR
) which I’d like to convert to FLOAT (10,6)
.
However there doesn’t appear to be a straightforward way to do this using CAST()
or CONVERT()
.
How can I convert these columns easily? This is a one-time conversion.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET latitude = CAST(old_latitude AS DECIMAL(10,6)), longitude = CAST(old_longitude AS DECIMAL(10,6));
Method 2
mysql> SELECT CAST(4 AS DECIMAL(4,3)); +-------------------------+ | CAST(4 AS DECIMAL(4,3)) | +-------------------------+ | 4.000 | +-------------------------+ 1 row in set (0.00 sec) mysql> SELECT CAST('4.5s' AS DECIMAL(4,3)); +------------------------------+ | CAST('4.5s' AS DECIMAL(4,3)) | +------------------------------+ | 4.500 | +------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3)); +-------------------------------+ | CAST('a4.5s' AS DECIMAL(4,3)) | +-------------------------------+ | 0.000 | +-------------------------------+ 1 row in set, 1 warning (0.00 sec)
Method 3
This will convert to a numeric value without the need to cast or specify length or digits:
STRING_COL+0.0
If your column is an INT
, can leave off the .0
to avoid decimals:
STRING_COL+0
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0