I\'ve got a question.
I have a decimal and I want to round this at 2 decimals, not at the ordinary way but
0.2013559322033898305084745763
desired result:
It sounds like you want a version of Math.Ceiling
, but which takes a number of decimal places. You could just multiply, use Math.Ceiling
, then divide again:
public static double CeilingWithPlaces(double input, int places)
{
double scale = Math.Pow(10, places);
double multiplied = input * scale;
double ceiling = Math.Ceiling(multiplied);
return ceiling / scale;
}
(If you only ever need 2 decimal places of course, you can hard-code the scale of 100, as Dennis_E's answer does.)
Now, two caveats about this:
That will always round up, i.e. away from negative infinity. So it would round -0.201 to -0.20. If you want to round away from 0, you may need to handle negative values separately, e.g. with
if (input < 0)
{
return -CeilingWithPlaces(-input, places);
}
Not directly, so you have to use a trick:
Math.Ceiling(x * 100) / 100;