Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MySQL adds extra digits to floats?

Tags:

mysql

I have a table of prices. Each price is a FLOAT with two digits after the dot. From some reason, when I use the price in IF expression, the result is the same float with many additional digits:

mysql> select price, IF(1, price,0) as my_price from tbl_prices limit 10;
+-------+------------------+
| price | my_price         |
+-------+------------------+
| 79.95 | 79.9499969482422 |
| 99.95 | 99.9499969482422 |
| 89.95 | 89.9499969482422 |
| 89.95 | 89.9499969482422 |
| 79.95 | 79.9499969482422 |
| 89.95 | 89.9499969482422 |
| 89.95 | 89.9499969482422 |
| 79.95 | 79.9499969482422 |
| 79.95 | 79.9499969482422 |
| 69.95 | 69.9499969482422 |
+-------+------------------+
10 rows in set (0.00 sec)

As you can see, price looks good, however the result of IF expression that returns the same price contains garbage.

Does anybody know what is the reason for this garbage, and how can I get rid of it (without using ROUND)?

Thanks in advance!

like image 451
diemacht Avatar asked Jan 17 '26 04:01

diemacht


1 Answers

Just don't. A float is not an exact value. Use DECIMAL fields for example for a price.

like image 99
Luc Franken Avatar answered Jan 19 '26 20:01

Luc Franken



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!