Reputation: 220
How can I round numbers up to the nearest whole or to the nearest half?
For Example:
> 23.15 --> 23.5
> 23.56 --> 24.0
The rounding functions I know about are floor
and ceil
, but those only round to the nearest integer.
Upvotes: 8
Views: 6236
Reputation: 16698
Why don't try this one, with any significance you want in the precision:
public double Ceiling(double value, double significance)
{
if ((value % significance) != 0)
{
return ((int)(value / significance) * significance) + significance;
}
return Convert.ToDouble(value);
}
Usage:
var d1 = Ceiling(23.15, 0.5); // 23.5
var d2 = Ceiling(23.56, 0.5); // 24.0
This function of Ceiling is used by Microsoft Excel, and to match this calculation i devised this algorithm.
Reference: Ceiling and Floor functions like Microsoft Excel in .NET
Upvotes: 4
Reputation: 2884
David's method pretty much seals it, but here is another lengthier way.
double dbNum = 3.44;
double dbNumModified = 3.44 + 0.5;
dbNumModified = Math.Floor(dbNum);
if(dbNumModified < dbNum)
{
dbNumModified += 0.5;
}
return dbNumModified;
Upvotes: 0
Reputation:
The quick and dirty way:
Multiply by 2, ceiling, and divide by 2. Quick and easy to understand, but this will fail on edge cases due to number overflow.
A more robust method is to cut off everything before the decimal before evaluating the round with the method above, and add the result to the whole number you cut off.
Upvotes: 3
Reputation: 27864
You want to round up, to a multiple of 0.5? Am I understanding that correctly?
double RoundUpToPointFive(double d)
{
return Math.Ceiling(d * 2) / 2;
}
Upvotes: 13