Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float type in MySQL

Tags:

sql

mysql

I have a MySQL table with column of type float(10, 6).

If I insert 30.064742 into the column the value stored in the database is 30.064741.

Why?

like image 866
PetrB Avatar asked Jul 05 '26 20:07

PetrB


2 Answers

Floating-point numbers imply a certain amount of imprecision. Use a DECIMAL column if you need to be certain to retain every digit.

like image 189
Ned Batchelder Avatar answered Jul 07 '26 08:07

Ned Batchelder


It's a general problem with rounding numbers to a precision which can be stored in the database. Floats will round to multiples of powers of two. If you want something that is easier to think about, you can use the Decimal type, which will round to powers of ten.

More details in the documentation for numeric types:

When such a column is assigned a value with more digits following the decimal point than are allowed by the specified scale, the value is converted to that scale. (The precise behavior is operating system-specific, but generally the effect is truncation to the allowable number of digits.)

like image 33
Douglas Avatar answered Jul 07 '26 09:07

Douglas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!