Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEEE 754 floating point arithmetic rounding error in c# and javascript

I just read a book about javascript. The author mentioned a floating point arithmetic rounding error in the IEEE 754 standard.

For example adding 0.1 and 0.2 yields 0.30000000000000004 instead of 0.3.

so (0.1 + 0.2) == 0.3 returns false.

I also reproduced this error in c#.

So these are my question is:

How often this error occurs? What is the best practice workaround in c# and javascript? Which other languages have the same error?

like image 444
Henk Avatar asked Jun 06 '26 21:06

Henk


2 Answers

It's not an error in the language. It's not an error in IEEE 754. It's an error in the expectation and usage of binary floating point numbers. Once you understand what binary floating point numbers really are, it makes perfect sense.

The best practice in C# is to use System.Decimal (aka decimal) which is a decimal floating point type, whenever you're dealing with quantities which are naturally expressed in decimal - typically currency values.

See my articles on .NET binary floating point and decimal floating point for more information.

like image 118
Jon Skeet Avatar answered Jun 08 '26 11:06

Jon Skeet


The error is NOT a rounding error, it's simply that some values cannot be exactly represented by the IEEE 754 standard. see Jon Skeet's article on binary floating point numbers in .net for further reading.

For dealing with numbers like your example (base-10) you should be using the decimal datatype in C# as it can represent these numbers exactly, so you get values you'd expect.

A typical way is to define some epsilon value, and check whether the result is within targetvalue +- epsilon:

double const epsilon = 0.000001; // or whatever

if(valueA >= valueB - epsilon && valueA <= valueB + epsilon)
{
    // treat as valueA = valueB
}
like image 23
George Duckett Avatar answered Jun 08 '26 11:06

George Duckett