Вопрос

I am looking for a way to round to the nearest dollar with the following stipulations:
(If wholenumber.50 and above round up to the next whole number)
(If wholenumber.49 and below round down to the current whole number)

I have tried:

Math.Round(wholenumber.xx, MidpointRounding.ToEven);

This doesn't always round how I want for instance 1.5 = 2 and 2.5 = 2 as it rounds to nearest even number.

I have also tried:

Math.Round(wholenumber.xx, MidpointRounding.AwayFromZero);

This always rounds up to the higher whole number.

Is there any built in functionality for what I am trying to do or will I need to write my own custom method to check the number and do floor or ceil depending?

Это было полезно?

Решение

First off, I note that you should always use decimal for this task; never use double. If you are using double, stop what you are doing right now and fix your program so that you stop using a type designed for physics problems and start using a type designed for money problems to solve your money problem.

Second, you are simply wrong when you say

This always rounds up to the higher whole number.

It does not. It rounds to the nearest whole number, and if there is no nearest whole number because you are at a midpoint, then it chooses the whole number that is farther from zero.

Try it, if you don't believe me:

using System;
class P
{
  static void Main()
  {
    decimal buckFifty = 1.50m;
    decimal buckFortyNine = 1.49m;
    Console.WriteLine(Math.Round(buckFortyNine, MidpointRounding.AwayFromZero));
    Console.WriteLine(Math.Round(buckFifty, MidpointRounding.AwayFromZero));
    Console.WriteLine(Math.Round(-buckFortyNine, MidpointRounding.AwayFromZero));
    Console.WriteLine(Math.Round(-buckFifty, MidpointRounding.AwayFromZero));
  }
}

results are

1
2
-1
-2
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top