How to combine decimal with a certain fraction in C #?

In C #, rounding a number is easy:

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

However, I want to round the number, so that the fractional part of the number is rounded to the nearest fractional part of the predefined fraction (for example, 1/8), 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 to an integer eighth, I would like 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 parameter is the number that I want to round, and the second parameter determines the rounding fraction. Thus, in this example, after rounding, the digits after the decimal point can be only one of eight values: .000, .125, .250, .375, .500, .625, .750, .875

Questions: is this feature embedded in .NET somewhere? If not, does anyone have a link to a resource that explains how to approach this problem?

+4
source share
2 answers

You can do it:

 Math.Round(n * 8) / 8.0 
+16
source

I don’t know if it is embedded in .NET, but I would just do:

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

round it to the nearest 8th.

Substitute your favorite number for other "permissions".

+5
source

All Articles