Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Math.Ceiling bug or not?

Tags:

c#

ceil

I do not know why Ceiling behave like in the below image

Why is processingFee != Settings.PaymentProcessingFeeInPercentage * prizesSum ?

View image at full size

alt text http://img514.imageshack.us/img514/3950/csharpceilingproblem.png

like image 400
Sorin Avatar asked Jul 01 '10 14:07

Sorin


2 Answers

Your percentage isn't actually 0.05. It's a value close to 0.05... and probably a little bit more than 0.05. Thus when it's multiplied by 2600, you're getting a value just over 130.0... which is then being "ceilinged" to 131.0.

Using a little tool I wrote a while ago (available from this page about .NET binary floating point types) it looks like the actual float value closest to 0.05 is 0.0500000007450580596923828125. For doubles, it's 0.05000000000000000277555756156289135105907917022705078125.

Moral of the story: don't use float for this sort of thing - use decimal. Or if you're just trying to represent a percentage, if it's okay to actually be only accurate to one percent, use an integer value 0-100.

like image 178
Jon Skeet Avatar answered Sep 30 '22 00:09

Jon Skeet


This is a result of the floating point representation of the numbers involved. See the wikipedia. Probably 0.05 has an infinite base 2 representation as a double, so the value Math.Ceiling actually sees might be slightly larger than 130.

like image 42
Jens Avatar answered Sep 30 '22 00:09

Jens