Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cast a DECIMAL to DOUBLE in MySQL?

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?

like image 222
c00kiemonster Avatar asked Oct 05 '12 08:10

c00kiemonster


People also ask

How do you convert decimal to DOUBLE?

You can also convert a Decimal to a Double value by using the Explicit assignment operator. Because the conversion can entail a loss of precision, you must use a casting operator in C# or a conversion function in Visual Basic.

How do you CAST decimals in SQL?

Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).

Can we use DOUBLE in MySQL?

DOUBLE is a double precision floating point number. MySQL uses eight bytes to store a DOUBLE value. MySQL treats DOUBLE as a synonym for DOUBLE PRECISION (a non-standard extension). In addition, MySQL also treats REAL as a synonym for DOUBLE PRECISION , unless the REAL_AS_FLOAT SQL mode is enabled.

Can we use CAST in MySQL?

The CAST() function in MySQL is used to convert a value from one data type to another data type specified in the expression. It is mostly used with WHERE, HAVING, and JOIN clauses. This function is similar to the CONVERT() function in MySQL. It converts the value into DATE datatype in the "YYYY-MM-DD" format.


2 Answers

SELECT my_decimal_field + 0E0 FROM my_table

The following quotes from MySQL manual explain how this works:

9.1.2 Numeric Literals

Number literals include exact-value (integer and DECIMAL) literals and approximate-value (floating-point) literals.

Numbers represented in scientific notation with a mantissa and exponent are approximate-value numbers.

12.22.3 Expression Handling

Handling of a numeric expression depends on what kind of values the expression contains:

  • If any approximate values are present, the expression is approximate and is evaluated using floating-point arithmetic.
like image 98
PowerGamer Avatar answered Oct 22 '22 18:10

PowerGamer


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
like image 2
Joel Karunungan Avatar answered Oct 22 '22 18:10

Joel Karunungan