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))
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))
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.
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
As you are trying to convert an integer (In your case its value is 1) into Decimal number DECIMAL(n,m) that have precision n i.e. total number of digit (n=4 in your case) and scale as m i.e. number of digits after decimal (m=4 in your case)
So In your case decimal number will range from (-0.9999 to 0.9999)
And so when you try to convert any integer > 0 it will be converted as 0.9999(Maximum possible value)
and when you try to convert any integer < 0 it will be converted as -0.9999(minimum possible value)
this kind of conversion will cause an error if server run in strict mode.