Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Rounding Issue

I have a rounding issue inside of .Net.

I am rounding a 3 digit number down to two digits and it is causing some problems with one number.

If I try to round 34.425 to two decimal places it should round it to 34.43. I am using the roundawayfromzero option and it has worked for every number in the program except for this one so far.

The code Math.Round(34.425, 2, MidpointRounding.AwayFromZero) should equal 34.43 however, it equals 34.42.

If I try this with any other number it works fine.

Math.Round(34.435, 2, MidpointRounding.AwayFromZero) = 34.44

Math.Round(34.225, 2, MidpointRounding.AwayFromZero) = 34.23

Math.Round(34.465, 2, MidpointRounding.AwayFromZero) = 34.47

I just wanted to check to see if anyone has run into this problem before?

For right now I have fixed this problem by converting the number to a decimal. I have changed the code to this and it works fine now:

Math.Round(CDec(34.425), 2, MidpointRounding.AwayFromZero) = 34.43

I am just looking for a reason on why my old code did not work.

Thank you!

Updated the code to the correct AwayFromZero

like image 224
Jeff Avatar asked Oct 19 '10 14:10

Jeff


People also ask

How do I stop rounding in C#?

Math. Truncate (x * 10.0) / 10.0 is one way to do it. Using your numbers: double x = 5.0 * (53.0 - 32.0) / 9.0; double result = Math.

What causes rounding error?

A rounding error, or round-off error, is a mathematical miscalculation or quantization error caused by altering a number to an integer or one with fewer decimals.

What does 2.5 round to?

Both 1.5 and 2.5 are rounded to 2 . 3.5 and 4.5 are rounded to 4 .

How does rounding work C#?

In C#, Math. Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method has another overload with which, you can specify the number of digits beyond the decimal point in the returned value.


2 Answers

Floating point is never exact, 34.425 may have an internal represantation 34.4249999999999.. which will be rounded up to 34.42.

If you need exact representation for numbers use the decimal type.

like image 152
codymanix Avatar answered Sep 20 '22 14:09

codymanix


Slightly confused about whether you're actually using MidpointRounding.ToEven or MidpointRounding.AwayFromZero. If you are using ToEven as the first snippet indicates, this is expected behavior.

like image 20
user470379 Avatar answered Sep 19 '22 14:09

user470379