简体   繁体   中英

Rounding-up a decimal to 2 decimal places

I have a problem to round a number to two decimal places.

I have the number 3106.4647771976413339683766317M.

The correct round to two decimal places is 3106.47, but using Math.Round(value, 2, MidpointRounding.AwayFromZero) the number is 3106.46.

The problem is the method look to third decimal place to round, but if it look to fourth decimal place will generate the correct number.

Someone has something like that?

Mathematically, the correct round to two decimal places is 3106.46.

What you probably want is a ceiling :

Math.Ceiling(3106.4647771976413339683766317M * 100) / 100

produces 3106.47. There is no version of Math.Ceiling accepting a number of decimal places, that's why there are multiplication and division.

In addition, note that there is a caveat in this expression:

Math.Round(value, 2, MidpointRounding.AwayFromZero) 

Math.Round does not have a variant with three arguments, where the first one is a decimal . It works, because the value is implicitly converted to double . However, this is unwanted.

If you really want to round that way (more of a common mistake than actual rounding in the traditional sense) you can round up from the furthest right digit and move left one place at a time.

double numberToRound = 3106.4647771976413339683766317;

int placesToRoundTo = 2;
int smallestPlaceIndex = 24; // you would need to determine this value

for (int i = smallestPlaceIndex; i >= placesToRoundTo)
{
    numberToRound = Math.Round(numberToRound, i, MidpointRounding.AwayFromZero);
}

There isn't a simple built-in method to do this because it isn't normal rounding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM