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?
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.
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).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With