Can anyone tell me why the following statement evaluates to false?
bool myBoolean = .6 + .3 + .1 == .1 + .3 + .6; // false
It does the same thing in Javascript and C++.
Can anyone tell me why the following statement evaluates to false?
bool myBoolean = .6 + .3 + .1 == .1 + .3 + .6; // false
It does the same thing in Javascript and C++.
Nb. I'm answering this question since it is also tagged C++
Due to float representation errors, in C++ the above yields false since the two float numbers aren't perfectly equal.
E.g. the internal representation for 0.1 is close to that value, but not exactly it
The same holds for C#.
Allow me to link a famous document that (imho) every programmer dealing with floating point arithmetic should read: What Every Computer Scientist Should Know About Floating-Point Arithmetic
]Never trust the Floating-Point Arithmetic
. During the conversion you can have a loss of precison. That's why the result is false. I suggest u try using the decimal type which stores numbers in decimal notation. Thus your numbers will be representable precisely.