Empty strings cannot be converted to a number for obvious reasons.
You have to account for that. Replace all occurrences with NULL
or 0
or something compatible.
For the number of fractional digits in your example you want the data type numeric
, not float - neither real
(float4
) nor double precision
(float8
). Those are lossy types and not exact enough. See:
Try for yourself:
SELECT '-73.88537758790638'::real AS _float4
,'-73.88537758790638'::double precision AS _float8
,'-73.88537758790638'::numeric AS _numeric;
Result (up to Postgres 11):
_float4 | _float8 | _numeric
---------+-------------------+-------------------
-73.8854 | -73.8853775879064 | -73.88537758790638
db<>fiddle here
Display improved in Postgres 12 (more extra_float_digits
by default):
db<>fiddle here
Solution
Single SQL statement (replacing empty strings with NULL
):
ALTER TABLE tbl
ALTER COLUMN col1 TYPE numeric USING NULLIF(col1, '')::numeric;