Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL MIN() strange value

I'm working on a small webshop and I'm trying to get the lowest price for a product (photos).

So I check to see what the lowest added price is (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 lowest 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 give is 1256.30004882813.
The value is set as a FLOAT.

Why is the result 1256.30004882813 and not 1256.3?

like image 942
Edy Elwood Avatar asked Dec 12 '11 14:12

Edy Elwood


1 Answers

Because the real number 1256.3 cannot be represented precisely in floating point.

You should be using a fixed-point datatype for monetary data. Quoting from the MySQL documentation:

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data.

like image 148
Daniel Vassallo Avatar answered Sep 29 '22 12:09

Daniel Vassallo