Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting 1 to decimal returns 0.9999 instead of 1.0000 in MySQL

Tags:

casting

mysql

When casting 1 to decimal in MySQL, I was expecting 1.0000, but instead the output is 0.9999.

What exactly is happening here?

SELECT CAST(1 AS DECIMAL(4,4))
like image 328
Zack Avatar asked Aug 28 '16 03:08

Zack


People also ask

How do I cast a number to a decimal 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).

How do I cast an int in MySQL?

To cast VARCHAR to INT, we can use the cast() function from MySQL. Here is the syntax of cast() function. For our example, we will create a table with the help of create command. Display all records with the help of select statement.


2 Answers

MySQL is clipping the converted value to the largest one that will fit in the target type. A decimal(4, 4) doesn't allot any significant digits to the left of the decimal place.

This cast does not cause overflow only when the server is not running a strict mode as described in the documentation.

like image 97
shawnt00 Avatar answered Oct 07 '22 04:10

shawnt00


out of range

For example, DECIMAL(5,2) store any value with five digits and two decimals, its range from -999.99 to 999.99.

SELECT CAST(1 AS DECIMAL(5,4)) -> 1.0000
SELECT CAST(1 AS DECIMAL(4,3)) -> 1.000
SELECT CAST(0.0001 AS DECIMAL(4,4)) -> 0.0001
SELECT CAST(0.00001 AS DECIMAL(4,4)) -> 0.0000
SELECT CAST(12345 AS DECIMAL(5,4)) -> 9.9999

More info:

https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html https://dev.mysql.com/doc/refman/5.7/en/fixed-point-types.html

like image 43
Anthony Zhan Avatar answered Oct 07 '22 05:10

Anthony Zhan