Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for equality on a MySQL Float field

Tags:

I have a Joomla system and I'm trying to change the search so that it correctly finds floating point values in the database.

So, I have a query that is built at runtime that looks something like this:

select 'column1'
from 'some_table'
where 'some_float_field' <=> '2.18'

This doesn't work, it never matches anything, even though I see records in the db with this value there.

So I tried to just do this instead:

select 'column1'
from 'some_table'
where 'some_float_field' <=> 2.18

No luck, so then I tried casting to a decimal (float doesn't work for some reason), so I tried this:

select 'column1'
from 'some_table'
where 'some_float_field' <=> CAST('2.18' AS DECIMAL(20, 2))

No dice...

Keep in mind that >= or <= returns the proper results, just <=> gives me issues.

How do I get equality to work here?

like image 582
Joseph Avatar asked Feb 02 '10 22:02

Joseph


People also ask

What does <> mean in MySQL?

MySQLi For Beginners The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0.

How do you 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 .

Is not equal to in MySQL?

not equal to (<>, !=) operator. MySQL Not equal is used to return a set of rows (from a table) after making sure that two expressions placed on either side of the NOT EQUAL TO (<>) operator are not equal.

What is the difference between FLOAT and double in MySQL?

FLOAT is a single precision floating point number. MySQL uses four bytes to store a FLOAT value. DOUBLE is a double precision floating point number. MySQL uses eight bytes to store a DOUBLE value.


2 Answers

Usually with these types of questions it's good to provide a small example to replicate your results.

Usually testing for exact float values is a bad idea since floating point precision isn't an exact science. It's much better to use some tolerance.

create table foo1 (col1 float);

insert into foo1 values (2.18);
select * from foo1 where abs(col1-2.18) <= 1e-6
like image 74
dcp Avatar answered Oct 29 '22 18:10

dcp


Here is an easy way to do this

Just write where some_float_field LIKE 2.18

Hope it will help ;)

like image 26
Neeraj Avatar answered Oct 29 '22 17:10

Neeraj