Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Value of 1 in DECIMAL(2, 2) is coming out as 0.99

Tags:

mysql

I am storing monetary values, and I read that FLOAT has internal rounding problems (although I can't say I ever noticed any problems) and that it is better to use DECIMAL.

So I have been using DECIMAL but when I try to set the value to 1 it is stored as 0.99. I will be using that value in JavaScript at some point, and I know that my JS calculations will be wrong because it is 0.99 not 1.00.

Why is it doing that and should I just use FLOAT?

like image 428
BadHorsie Avatar asked Sep 12 '11 13:09

BadHorsie


People also ask

What is the default value decimal in MySQL?

MySQL supports both of these variant forms of DECIMAL syntax. The default value of M is 10. If the scale is 0, DECIMAL values contain no decimal point or fractional part.

How do I show decimal values 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).

What does decimal mean in MySQL?

In MySQL, the DECIMAL and NUMERIC data types store exact, fixed-point values. In MySQL, NUMERIC is implemented as a DECIMAL, so a NUMERIC and DECIMAL are the same data type. This data type is used when it is important to preserve the exact precision, such as storing money data.


1 Answers

You need DECIMAL(4, 2) by the looks of things. DECIMAL(2, 2) only allows a range of -0.99 to 0.99

The precision represents the number of significant digits that are stored for values, and the scale represents the number of digits that can be stored following the decimal point. so in your case you have not defined the column to allow any integer part at all.

like image 69
Martin Smith Avatar answered Sep 21 '22 20:09

Martin Smith