Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I stop mysql from rounding float values?

I'm storing monetary values in a mysql table as floats.

problem being, mysql is rounding the numbers up or down.

ex. 12345.68 gets rounded to 12345.7

How can I stop this or is there a better data type I should be using?

I would like to retain the original values within the 2 decimal places.

like image 616
Mike Volmar Avatar asked Jan 05 '17 18:01

Mike Volmar


2 Answers

Do not use FLOAT type. Use DECIMAL instead. Float converts decimal numbers to binary which results in rounding (loss of precision). Decimal stores the numbers as decimals - no conversion.

In your case defining the column as DECIMAL(12,2) should be ok. Chose the width (first number) based on the expected size of the numbers. In the example, the expected size is 12 digits (including the digits after the decimal point).

like image 73
Ivan Georgiev Avatar answered Sep 19 '22 15:09

Ivan Georgiev


Change the definition of the applicable column from its current setting to:

FLOAT(9,2)

The 2 in the previous snippet instructs MySQL to maintain values up to 2 decimal places. It's likely set to 1 at the moment; thus the observed behavior. Feel free to change the 9 to a more applicable value.

More on floats and precision.

Related answer, which advises on not using floats, but instead decimal.

like image 36
Alex Avatar answered Sep 21 '22 15:09

Alex