C # weird behavior with + operator

Can someone tell me why the following statement evaluates to false?

bool myBoolean = .6 + .3 + .1 == .1 + .3 + .6; // false 

It does the same in Javascript and C ++.

+5
source share
2 answers

<sub> Nb. I answer this question as it is also tagged with C ++

Due to errors in representing the float in C ++, the above gives false, since the two floating-point numbers are not quite equal.

eg. the internal representation for 0.1 is close to this value, but not exactly that

enter image description here

The same is true for C #.

Let me relate a well-known document that (imho), every programmer engaged in floating point arithmetic should read: What every computer scientist should know about floating point Arithmetic

+7
source

] Never trust Floating-Point Arithmetic . You may lose accuracy during the conversion. That is why the result is false. I suggest you try using the decimal type, which stores numbers in decimal notation. This way your numbers will be accurately represented.

enter image description here

0
source

All Articles