How can I multiply two decimals and round the result down to 2 decimal places?
For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c
As of .NET Core 3.0
and the upcoming .NET Framework 5.0
the following is valid
Math.Round(41.75 * 0.1, 2, MidpointRounding.ToZero))
This is my Float-Proof Round Down.
public static class MyMath
{
public static double RoundDown(double number, int decimalPlaces)
{
string pr = number.ToString();
string[] parts = pr.Split('.');
char[] decparts = parts[1].ToCharArray();
parts[1] = "";
for (int i = 0; i < decimalPlaces; i++)
{
parts[1] += decparts[i];
}
pr = string.Join(".", parts);
return Convert.ToDouble(pr);
}
}
One more solution is to make rounding toward zero from rounding away from zero. It should be something like this:
static decimal DecimalTowardZero(decimal value, int decimals)
{
// rounding away from zero
var rounded = decimal.Round(value, decimals, MidpointRounding.AwayFromZero);
// if the absolute rounded result is greater
// than the absolute source number we need to correct result
if (Math.Abs(rounded) > Math.Abs(value))
{
return rounded - new decimal(1, 0, 0, value < 0, (byte)decimals);
}
else
{
return rounded;
}
}
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
The Math.Round(...)
function has an Enum to tell it what rounding strategy to use. Unfortunately the two defined won't exactly fit your situation.
The two Midpoint Rounding modes are:
What you want to use is Floor
with some multiplication.
var output = Math.Floor((41.75 * 0.1) * 100) / 100;
The output
variable should have 4.17 in it now.
In fact you can also write a function to take a variable length as well:
public decimal RoundDown(decimal i, double decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(i * power) / power;
}
There is no native support for precision floor/ceillin in c#.
You can however mimic the functionality by multiplying the number, the floor, and then divide by the same multiplier.
eg,
decimal y = 4.314M;
decimal x = Math.Floor(y * 100) / 100; // To two decimal places (use 1000 for 3 etc)
Console.WriteLine(x); // 4.31
Not the ideal solution, but should work if the number is small.