How to round to half, always in positive direction? [closed]
How do I achieve the below rounding?
0.012608376 > 0.015
2.1 > 2.5
2.4 > 2.5
2.5 > 2.5
2.6 > 3
.01 > .05
public double Round(double input, int decimalPlaces)
{
double precision = 2.0 * Math.Pow(10, decimalPlaces - 1);
// Ceiling also rounds negative values in positive direction
return Math.Ceiling(x * precision) / precision;
}
Use like this:
Round(0.012608376, 3) returns 0.015
Round(2.1, 1) returns 2.5
Round(2.4, 1) returns 2.5
Round(2.5, 1) returns 2.5
Round(2.6, 1) returns 3
Round(.01, 2) returns .05
Better to be used with decimals, by the way.
static double RoundHalfUp(double value) {
var scale = 1.0;
while (value * scale < 0.1) scale *= 10;
return Math.Ceiling(value * 2) / (2 * scale);
}
Sample code. This doesnt take into account special cases at all, and yes, it fails your first case as it isn't clear what you want. Refine the question please.
Take the decimal place that you want to round at. If that greater than 5 round up. If less than 5 round down and add 5 (to that decimal place), if equal to 5 do nothing.
2.1 > round down to 2.0 > add .5 > 2.5
2.4 > round down to 2.0 > add .5 > 2.5
2.5 > 2.5
2.6 > round up 3
This is difficult because you are never rounding on the same decimal place. Is there not a better way to do this? You shouldn't be rounding data to a different place depending on how many decimal points it is. For instance, you should always round to tenths, or always round to hundredths, not round there dependent on the data.
精彩评论