开发者

Multiplying a double by 100 in C# leads to unexpected answer [duplicate]

开发者 https://www.devze.com 2023-04-09 05:32 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: C# Maths gives wrong results!
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消