Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a float in MySQL

I am trying to do a SELECT match on a table based upon an identifier and a price, such as:

SELECT * FROM `table` WHERE `ident`='ident23' AND `price`='101.31'; 

The above returns zero rows, while if you remove the price='101.31' bit it returns the correct row.

Doing a...

SELECT * FROM `table`; 

Returns the same row as above and quite clearly states that price='101.31'. Yet select fails to match it. Changing = to <= makes it work - but this is not exactly a solution.

Is there a way of casting the MySQL float to 2 digits before the operation is performed on it, thus making the above SELECT work (or some other solution)?

Thanks!

like image 424
Meep3D Avatar asked Aug 19 '09 19:08

Meep3D


People also ask

How do you define a FLOAT in MySQL?

MySQL permits a nonstandard syntax: FLOAT( M , D ) or REAL( M , D ) or DOUBLE PRECISION( M , D ) . Here, ( M , D ) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) is displayed as -999.9999 .

What is %s and %D in MySQL?

%d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.


2 Answers

Casting to a decimal worked for me:

SELECT * FROM table WHERE CAST(price AS DECIMAL) = CAST(101.31 AS DECIMAL); 

However, you may want to consider just making the price column a DECIMAL in the first place. DECIMAL is generally considered to be the best type to use when dealing with monetary values.

like image 146
Matt Solnit Avatar answered Sep 21 '22 21:09

Matt Solnit


It doesn't work because a float is inherently imprecise. The actual value is probably something like '101.3100000000001' You could use ROUND() on it first to round it to 2 places, or better yet use a DECIMAL type instead of a float.

like image 30
Eric Petroelje Avatar answered Sep 19 '22 21:09

Eric Petroelje