Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong calculation in SQL-Server

Tags:

sql-server

As an example I found a simple calculation like:

select cast(200.00 as float) + 1908.30 + 170.00 + (-1150.00) + (-1128.30)

As a normal addition this results in 0.00 but SQL Server shows the result as 2.27373675443232E-13.

Why is this and how can I avoid this?

like image 726
Ice Avatar asked Sep 08 '25 01:09

Ice


2 Answers

This error is inherent in the float datatype, and is the reason for the existence of decimal type. Never do money calculations as float values!

You can take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic, or any Google result for "float rounding error".

like image 82
Amadan Avatar answered Sep 09 '25 23:09

Amadan


select cast(200.00 as decimal(10,2)) + 1908.30 + 170.00 + (-1150.00) + (-1128.30)
like image 29
alexl Avatar answered Sep 10 '25 01:09

alexl