views:

2065

answers:

2

In C# rounding a number is easy:

Math.Round(1.23456, 4); // returns 1.2346

However, I want to round a number such that the fractional part of the number rounds to the closest fractional part of a predefined fraction (e.g. 1/8th) and I'm trying to find out if the .NET library already has this built in.

So, for example, if I want to round a decimal number to a whole eighth then I'd want to call something like:

Math.RoundFractional(1.9, 8); // and have this yield 1.875
Math.RoundFractional(1.95, 8); // and have this yield 2.0

So the first param is the number that I want to round and the second param dictates the rounding fraction. So in this example, after rounding has taken place the figures following the decimal point can only be one of eight values: .000, .125, .250, .375, .500, .625, .750, .875

The Questions: Is this function built into .NET somewhere? If not, does anybody have a link to a resource that explains how to approach solving this problem?

+9  A: 

You could do this:

Math.Round(n * 8) / 8.0
Greg Hewgill
Thanks Greg - I hate it when my brain's on vacation.
Guy
No worries, that's what SO is for. :)
Greg Hewgill
This just seems to simple to be right! Thanks Greg, this is just what I needed ;-)
Nic
+4  A: 

Don't know if it's built into .NET but I would simply do:

Math.Round(x * 8, 0) / 8;

to round it to the nearest 8th.

Substitute your favorite number for other "resolutions".

paxdiablo