1

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?

MikeTWebb
  • 9,149
  • 25
  • 93
  • 132
  • 1
    Refer to this question: http://stackoverflow.com/questions/977796/in-c-math-round2-5-result-is-2-instead-of-3-are-you-kidding-me – Andrei Dvoynos Sep 19 '12 at 21:35

5 Answers5

6

Use the overload that takes a MidpointRounding

Math.Round(276.5, MidpointRounding.AwayFromZero);

demo: http://ideone.com/sQ26z

Tim Schmelter
  • 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
4

As already mentioned, you can use Math.Round(d, MidpointRounding.AwayFromZero).

By default, .NET uses the so called bankers rounding (or MidpointRounding.ToEven)

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
2

.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);
KeithS
  • 70,210
  • 21
  • 112
  • 164
0

Use:

Math.Round(value, MidpointRounding.AwayFromZero);
NominSim
  • 8,447
  • 3
  • 28
  • 38
-1

Try using Math.Ceiling instead

Johnny
  • 785
  • 1
  • 7
  • 16