2004-10-20

Rounding a floating point value to a certain precision

For my work, I needed to round a floating point value (double in C#) to a precision of 0.05. Unfortunately, Math.Round only lets you round a value to the nearest decimal. That means you can only round to 0.1, 0.01, 0.001, ... To round your values to 0.05, or 0.25, or whatever, I created the following function:
In C#:
public static double Round(double x, int numerator, int denominator)
{ // returns the number nearest x, with a precision of numerator/denominator
 // example: Round(12.1436, 5, 100) will round x to 12.15 (precision = 5/100 = 0.05)
 long y = (long)Math.Floor(x * denominator + (double)numerator / 2.0);
 return (double)(y - y % numerator)/(double)denominator;
}
In Euphoria:
global function Round(atom x, integer numerator, integer denominator)
 -- returns the number nearest x, with a precision of numerator/denominator
 -- example: Round(12.1436, 5, 100) will round x to 12.15 (precision = 5/100 = 0.05)
 integer y
 y = floor(x * denominator + numerator / 2.0)
 return (y - remainder(y, numerator)) / denominator
end function
Comments:
Hey man. I was just about to write this very thing, then thought to myself "I bet someone already did this." Google and tommy pulled through to save me the trouble. Thanks bro.
 
I created the function, because I needed it for an interactive chart component, where you can drag certain points to new values, but the values had to be rounded to 0.05.
And I thought this simple function could be useful for other people too.
 
Since what i really wanted was the ability to provide a single interval value to round to (e.g., round to the nearest .05), without figuring out the num and denom each time, i decided to take a stab at it. Not that you'd need it anymore, but here's the result ...


public static double RoundToInterval(double x, double interval)
{
// round to the nearest specified interval value
if ( interval != 0 )
{
// divide by the interval, round to the nearest whole number, then multiply by the interval
return (Math.Round(x /interval)*interval);
}
// can't divide by 0. return the number without rounding
return x;
}
 
Thnx so much...U saved my day
 
0.5625 wont work
in return (Math.Round(x /interval)*interval);
Ans = .55 when it should be .60
 
a confusion here. Why rounding of 0.5625 to nearest 0.05 sud return 0.60?
I guess 0.55 is right answer. Isn't it? Please suggest.

-Nirmal
 
yes..I agree with sancho....5625 has to return .6 as it has to round up...but not working unfortunately
 
Folks!
The plumbing is already done in the .NET Math.Round() method.

The following method would do the trick with least plumbing

public static double RoundToFraction(double x, double fraction)
{
int multiplier = (int)( 1.0 / fraction );
return Math.Round(multiplier * x, System.MidpointRounding.AwayFromZero) / multiplier;
}
 
Post a Comment

Links to this post:

Create a Link