Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up to 2 decimal places in C#

Tags:

c#

math

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.

like image 871
Chris Avatar asked Aug 16 '11 08:08

Chris


People also ask

How do you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

What is 2f in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

How do I get 2 decimal places in C++?

We use the %. 2f format specifier to display values rounded to 2 decimal places.


2 Answers

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.

like image 141
MikeBaker Avatar answered Oct 09 '22 22:10

MikeBaker


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.

like image 43
paxdiablo Avatar answered Oct 09 '22 21:10

paxdiablo