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?
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.
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.
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.
You could do this:
Math.Round(n * 8) / 8.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With