Rounding up to 2 decimal places in C# [duplicate]

2019-01-08 01:35发布

问题:

This question already has an answer here:

  • Have decimal amount, want to trim to 2 decimal places if present 4 answers

I have a decimal number which can be like the following:

189.182

I want to round this up to 2 decimal places, so the output would be the following:

189.19

Is there built in functionality for this in the Math class, or something else? I know the ceiling function exists but this doesn't seem to do what I want - it'll round to the nearest int, so just '189' in this case.

回答1:

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.



回答2:

You can use:

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

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



回答3:

How about

0.01 * ceil(100 * 189.182)


标签: c# math