How do I divide a decimal with fixed places, rounded down?

I use .NET 5.0. I want to divide a decimal x by an int y and keep the decimal place d, rounded down.

For example, If I want the decimal place is 3, 1M / 3 = 0.333M, 1M / 7 = 0.142M, etc. Of course 1M / 8 = 0.125M, 1M / 2 = 0.5M.

Do I have a way to do this other than like Math.Floor(x * (int)Math.Pow(10, d) / y) / (int)Math.Pow(10, d)?

Upvotes: 0

Views: 125

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38777

As of .NET Core 3.0, you can use MidpointRounding.ToZero (docs):

The strategy of directed rounding toward zero, with the result closest to and no greater in magnitude than the infinitely precise result.

decimal x = 1M;
int y = 7;
int d = 3;
decimal result = decimal.Round(x / y, d, MidpointRounding.ToZero);
Console.WriteLine(result); // outputs 0.142

Try it online

Upvotes: 2

Related Questions