Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding decimal value

I am facing problem while rounding the decimal value in C# using Math.Round(a, 2);

When I'm rounding 1.275 by 2 decimal points, the result is 1.27. When I'm doing the same for 1.375, the result is 1.38.

Why is it not rounding 1.275 to 1.28?

Thanks

like image 733
Shivi Avatar asked Jul 31 '12 13:07

Shivi


People also ask

Should 0.5 be rounded up?

Round Half Away From 0 For this method, 0.5 rounds the number so it is further away from zero, like this: 7.6 rounds away to 8. 7.5 rounds away to 8. 7.4 rounds to 7.

Does .05 round up or down?

Whenever the value right after the decimal is less than 5, we round down; otherwise, we round up.

Does 3.5 round up or down?

Answer: 3.5 rounded upto a whole number is 4. Round up always means to come to the next integer. 3.1, 3.2, 3.9, 3.001 all rounded up to 4.

Does 1.5 round up or down?

For example, 1.5 (pronounced as "one point five" or "one and a half") would be rounded up to 2, and 2.1 would be rounded down to 2.


1 Answers

I cannot reproduce your problem:

Math.Round(1.275m, 2) => 1.28m
Math.Round(1.375m, 2) => 1.38m

I suspect that your claim that you use a decimal value is false, and that you use double value instead. double can't represent many decimal values exactly, so when you write 1.275, it's actually 1.27499... 1.375 is one of the few representable onces, so it's actually 1.375.

If your code cares about exact decimal representation, for example when you work on money, you must use decimal and not binary floating point such as double or float.


But even if you use decimal representation, rounding behaves unexpectedly for many users:

Math.Round(1.265m, 2) => 1.26m
Math.Round(1.275m, 2) => 1.28m

By default Math.Round uses MidpointRounding.ToEven, also known as Banker's round. This avoids accumulating a bias from always rounding up at .5.

You can use an overload of Round that takes a rounding mode, and set it to AwayFromZero to get the behaviour you expect.

Math.Round(1.275m, 2, MidpointRounding.AwayFromZero) => 1.28m
like image 78
CodesInChaos Avatar answered Sep 21 '22 15:09

CodesInChaos