-2

I have a list of latitude and longitudinal values in my table of type varchar. I want them to be float. How do I convert varchar to float?

For example:
36.26056695 of type varchar should be converted 36.26056695 of type float.

-99.11080846 of type varchar should be converted -99.11080846 of type float

DeadChex
  • 4,379
  • 1
  • 27
  • 34

2 Answers2

2

Use Cast operator

For Example

SELECT CAST( '36.26056695' AS float) FROM TABLE

devil1212
  • 13
  • 2
1

That depends on what you mean by "losing data".

If you mean without loss of precision, "float" will be unreliable; it can only reliably store multiples of a power of two (.125, .25, .375, etc....)

If you just mean convert the fields without them going blank, the best bet is something like this:

ALTER TABLE `the_table` 
   ADD COLUMN `dec_val` NOT NULL DECIMAL(11, 8)
;

UPDATE `the_table` 
   SET `dec_val` = CAST(`str_val` AS DECIMAL(11, 8))
;

ALTER TABLE `the_table` 
   DROP COLUMN `str_val`
;

-- The below is only needed if you wanted to do something like rename the 
-- new column to the same name as the original. Otherwise, you could just
-- have created the new column with the desired name.
ALTER TABLE `the_table` 
   CHANGE COLUMN `dec_val` `desired_column_name` NOT NULL DECIMAL(11, 8)
; 

You could use FLOAT instead of DECIMAL of course, but this way preserves the exact values.

Note: Just changing the original column's definition to DECIMAL(11, 8) might work, but this allows you to inspect the converted values (after the UPDATE) before you drop the original ones.

Uueerdo
  • 15,723
  • 1
  • 16
  • 21