Possible Duplicate:
C# Maths gives wrong results!
I have the following code in my C# windows application projec开发者_如何学JAVAt:
double test = 2.24 * 100;
If I add a watch to test, one would expect the value to be 224, however it is actually: 224.00000000000003
can anyone explain where the extra .00000000000003 comes from?
Multiplying a decimal by 100 in C# leads to unexpected answer
Firstly, you haven't multiplied a decimal - you've multiplied an IEEE 754 floating-point number by 100.
Because 2.24 does not exist as a double
. However, if you do:
decimal test = 2.24M * 100;
it will behave as you expect.
This is behavior by design, this is how floating point numbers work - the precision is actually limited. See Floating Point Numbers - Accuracy Problems
It's a rounding error, not all numbers can be represented exactly in a double
Many others have explained this already, far more eloquently than I could. Try these links on for size:
Simple explanation
Advanced explanation
If that still leaves you scratching your head, just <insert favourite search engine> for "What every programmer should know about floating-point arithmetic"
Your getting the result because 2.24 is not an exact number. There are a more significant figures beyond just the 2 you provided. I would try a multiplication by 100.00 that and then round the number using only 3 significant figures.
I should make the clarification that you need to be using a decmial variable not a double. A double cannot represent an exact value.
精彩评论