Long story short, if you need to compare floating point numbers against columns defined as REAL you need to first cast them to NUMERIC in PostgreSQL. And to compare equality between two numbers with different amount of significant figures you have to use ROUND().

Less or greater is obvious to work with because it doesn't require the same precision:


mobilexpenses=# select vat from expenses where vat >= 18.98 and vat <= 20.0 ;
  vat   
---------
 19.6596
(1 row)

So there's a record there with vat ~= 19.66, doing an exact select on that won't work:


mobilexpenses=# select vat from expenses where vat = 19.6596;
 vat 
-----
(0 rows)

Why?? Well, you should never compare floating point numbers for equality. So what's the solution then? Solution: cast it to numeric and use round() depending on your comparison nature:


 mobilexpenses=# select vat from expenses where vat::numeric = 19.6596;
  vat   
---------
 19.6596
(1 row)

And if you want to compare it with 19.66?:


mobilexpenses=# select vat from expenses where vat::numeric = 19.66;
 vat 
-----
(0 rows)

Time to take out the ROUND() function:


mobilexpenses=# select vat from expenses where round(vat::numeric, 2) = 19.66;
  vat   
---------
 19.6596
(1 row)

Comments

Your email will never ever be published.

Previous:
A Flash interface that doesn't suck February 4, 2007 Web development
Next:
Vista voice recognition and Perl February 9, 2007 Misc. links
Related by category:
set -ex - The most useful bash trick of the year August 31, 2014 Linux
brotli_static in Nginx November 8, 2024 Linux
Be very careful with your add_header in Nginx! You might make your site insecure February 11, 2018 Linux
Linux tip: du --max-depth=1 September 27, 2007 Linux
Related by keyword:
Interesting float/int casting in Python April 25, 2006 Python
Calculator in Python for dummies December 17, 2007 Python
Formatting numeric amounts in Javascript January 16, 2009 JavaScript