问题
I know all the numerical implications, that is, the possible rounding issues inherent to floating point formats, but in my case I have DECIMAL
columns in MySQL
that I want to convert to DOUBLE
straight in the MySQL
query rather than down stream.
Could anyone help?
回答1:
SELECT my_decimal_field + 0E0 FROM my_table
回答2:
It seems not possible to cast it to DOUBLE
which brings problems if you do calculations and for example want to ROUND()
a DECIMAL 12,2
in the third digit. Using ROUND(foo * bar,2)
will just ignore the additional digits if your foo
and bar
are DECIMAL 12,2 fields.
That said you can do something like this to still make it work:
ROUND(CAST(foo AS DECIMAL(30,15)*CAST(bar AS DECIMAL(30,15)),2)
回答3:
Because of the limitations of the built in CAST
function in MySQL, it is only possible to convert DECIMAL
to DOUBLE
with your own user defined cast function.
Sample use case:
SELECT castDecimalAsDouble(0.000000000000000000100000000000);
Result: 1e-23
CREATE DEFINER=`root`@`localhost` FUNCTION `castDecimalAsDouble`(
decimalInput DECIMAL(65,30) ) RETURNS double
DETERMINISTIC
BEGIN
DECLARE doubleOutput DOUBLE;
SET doubleOutput = decimalInput;
RETURN doubleOutput;
END
回答4:
DECIMAL may save space. For example, DECIMAL(4,2)
occupies only 2 bytes. FLOAT
takes 4; DOUBLE
takes 8.
As for the original question, simply do:
ALTER TABLE t MODIFY COLUMN c DOUBLE ...;
(The "..." should include the other stuff you already had, such as NOT NULL
.)
来源:https://stackoverflow.com/questions/12742322/is-it-possible-to-cast-a-decimal-to-double-in-mysql