Why is 4/5 equal to zero?


Short answer: dividing two integers yields integer result

Since both 4 and 5 are integers, according to SQL standard, the result also has to be an integer. As the result is 0.8 it equals to zero. Firebird does not round up when value is bigger than 0.5, so you won't get result of one.

If you wish to get something like 0.8, you should use such datatype. For example, a query like 4.0/5 would work:

SQL> select 4/5 from rdb$database;
=====================
0

SQL> select 4.0/5 from rdb$database;
=====================
0.8

SQL> select 4/5.0 from rdb$database;
=====================
0.8

SQL> select 4.0/5.0 from rdb$database;
=====================
0.80

As you can see it these examples, the number of decimals in result is the sum of decimals of values involved. Here's another example to show why is that important:

SQL> select 2/3 from rdb$database;
=====================
0

SQL> select 2.0/3 from rdb$database;
=====================
0.6

SQL> select 2/3.0 from rdb$database;
=====================
0.6

SQL> select 2.0/3.0 from rdb$database;
=====================
0.66

When you work with columns instead of numeric constants, you should cast them to desired datatypes. For example:

SQL> select cast(2 as decimal(18,1))/cast(3 as decimal(18,1)) from rdb$database;
=====================
0.66

It's a common mistake to try something like this:

select cast(2/3 as decimal(18,2)) from rdb$database;
=====================
0.00

It does not work (well, it does, but not the way you would want) because CAST happens after the integer calculation.


Do you find this FAQ incorrect or incomplete? Please e-mail us what needs to be changed. To ensure quality, each change is checked by our editors (and often tested on live Firebird databases), before it enters the main FAQ database. If you desire so, the changes will be credited to your name. To learn more, visit our add content page.

If you are a commercial tool maker and your tool features a great way to handle the issue written about in this FAQ, please check out our advertisement page.



All contents are copyright © 2007-2017 FirebirdFAQ.org unless otherwise stated in the text.


Links   Firebird   News   FlameRobin   Home Inventory powered by FB  
Add content   Advertise   About  

Categories
 Newbies
 SQL
 Installation and setup
 Backup and restore
 Performance
 Security
 Connectivity and API
 HOWTOs
 Errors and error codes
 Miscellaneous