SQL MIN () weird value

I am working on a small online store and I am trying to get the lowest price for the product (photos).

So, I check what the lowest added price (photos can be ordered in different sizes):

SELECT MIN(price) as price FROM rm_prices WHERE photo_id = '47' AND price != '0' 

This returns the smallest value found for this product.

When I check my db, I see that the lowest value is 1256.3.
When I print my result, the number gives 1256.30004882813.
The value is set as FLOAT.

Why is the result 1256.30004882813 and not 1256.3?

+7
source share
3 answers

Because the valid number 1256.3 cannot be represented exactly in floating point .

For monetary data, you must use a fixed point data type . Quoting from the MySQL documentation :

The DECIMAL and NUMERIC types store exact values โ€‹โ€‹of numeric data. These types are used when it is important to maintain accurate accuracy, for example, with monetary data.

+11
source

This is a side effect of the FLOAT column type, you can try to save your prices in the DECIMAL data type, see the mysql manual for more information about this: http://dev.mysql.com/doc/refman/5.1/en/fixed- point-types.html

+5
source

1256.3 does not have an exact representation in floating point arithmetic; for this reason, it is usually best to store amounts of money as INTEGER or DECIMAL data types.

More information can be found here .

+1
source

All Articles