Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a decimal to a specific fraction in C#?

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?

like image 681
Guy Avatar asked Feb 02 '09 02:02

Guy


People also ask

How do you round in C programming?

round() is used to round a floating number to its nearest integer value whereas trunc() is used to remove the decimal values from a number. With this, you have the complete knowledge of rounding and truncating a number in C.

How do you round up C sharp?

In C#, Math. Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits.

How do you convert a decimal to a fraction in CPP?

eg:- how to convert any number X in the form p/q? Find out what is your fraction in base 10, e.g. 0.75 = 75/100, 0.085 = 85/1000 Divide both numerator and denominator by __gcd(numerator, denominator) to simplify the fraction.


1 Answers

You could do this:

Math.Round(n * 8) / 8.0
like image 79
Greg Hewgill Avatar answered Nov 09 '22 23:11

Greg Hewgill