MikeTWebb
MikeTWebb

Reputation: 9279

Rounding in C#. Net

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?

Upvotes: 1

Views: 288

Answers (5)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14581

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

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

Upvotes: 4

KeithS
KeithS

Reputation: 71565

.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);

Upvotes: 2

NominSim
NominSim

Reputation: 8511

Use:

Math.Round(value, MidpointRounding.AwayFromZero);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460068

Use the overload that takes a MidpointRounding

Math.Round(276.5, MidpointRounding.AwayFromZero);

demo: http://ideone.com/sQ26z

Upvotes: 6

Johnny
Johnny

Reputation: 795

Try using Math.Ceiling instead

Upvotes: -1

Related Questions