Rounding up to 2 decimal places in C#

Multiply by 100, call ceiling, divide by 100 does what I think you are asking for

public static double RoundUp(double input, int places)
{
    double multiplier = Math.Pow(10, Convert.ToDouble(places));
    return Math.Ceiling(input * multiplier) / multiplier;
}

Usage would look like:

RoundUp(189.182, 2);

This works by shifting the decimal point right 2 places (so it is to the right of the last 8) then performing the ceiling operation, then shifting the decimal point back to its original position.


You can use:

decimal n = 189.182M;
n = System.Math.Ceiling (n * 100) / 100;

An explanation of the various rounding functions can be found here.


Be aware that formulae like this are still constrained by the limited precision of the double type, should that be the type you are using (your question stated decimal but it's possible you may just have meant a floating point value with fractional component rather than that specific type).

For example:

double n = 283.79;
n = System.Math.Ceiling (n * 100);

will actually give you 28380, not the 283.79 you would expect(a).

If you want accuarate results across the board, you should definitely be using the decimal type.


(a) This is because the most accurate IEEE754 double precision representation of 283.79 is actually:

 283.790000000000020463630789891

That extra (admittedly minuscule) fractional component beyond the .79 gets ceilinged up, meaning it will give you a value higher than you would expect.


How about

0.01 * ceil(100 * 189.182)

Tags:

C#

Math