I have an MVC3 C#.Net web app. The product of a calculation is 158 * 1.75 = 276.5. I want this number to round up to 277. I am using Math.Round but it rounds down. I know I've seen this issue before somewhere. What's the solution?
5 Answers
Use the overload that takes a MidpointRounding
Math.Round(276.5, MidpointRounding.AwayFromZero);
demo: http://ideone.com/sQ26z

- 450,073
- 74
- 686
- 939
-
It is interesting to note that if you use a format string to convert the number to a string representation with zero decimals, that is `string output = (276.5).ToString("F0");`, then the away-from-zero rule is also used. I don't think that the to-even rule is ever used when string formatting a number. – Jeppe Stig Nielsen Sep 19 '12 at 21:47
As already mentioned, you can use Math.Round(d, MidpointRounding.AwayFromZero)
.
By default, .NET uses the so called bankers rounding (or MidpointRounding.ToEven
)

- 14,391
- 32
- 45
.NET uses bankers' rounding by default; it rounds values ending in 5 to the nearest even significant digit, and not always up (called "semantic arithmetic rounding"). The reason is that if you round a bunch of random decimal numbers and then sum them, when using banker's rounding that sum will be closer to the sum of the unrounded numbers than the sum of arithmetically-rounded numbers would be.
To force it to use grade-school rounding rules, use the overload accepting a MidpointROunding enum value:
Math.Round(myNumber, MidpointRounding.AwayFromZero);

- 70,210
- 21
- 112
- 164
Try using Math.Ceiling instead

- 785
- 1
- 7
- 16
-
1
-
@NominSim...that is true 276.1 should be 276 and 276.5 should be 277 – MikeTWebb Sep 19 '12 at 21:56