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
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.
Whenever the value right after the decimal is less than 5, we round down; otherwise, we round up.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With