Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this simple calculation of two doubles inaccurate? [duplicate]

Possible Duplicate:
C# (4): double minus double giving precision problems

86.25 - 86.24 = 0.01

generally, I would think the above statement is true right?

However, if I enter this

        double a = 86.24;
        double b = 86.25;
        double c = b - a;

I find that c = 0.010000000000005116

Why is this?

like image 703
Diskdrive Avatar asked Feb 25 '23 18:02

Diskdrive


1 Answers

Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg's What every computer scientist should know about floating-point arithmetic

This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, ... This is essential reading for any developer working with floating point arithmetic.

As VinayC suggests, if you need an exact (and slower) representation, use System.Decimal (aka decimal in C#) instead.

like image 111
James Kovacs Avatar answered Apr 12 '23 23:04

James Kovacs