我该如何计算两个小数并将结果向下舍入至小数点后两位?
例如,如果方程式为 41.75 x 0.1,则结果将为 4.175。如果我在 C# 中使用 decimal 进行计算,它会自动四舍五入到 4.18。但我希望将其向下取整为 4.17。
我尝试使用 Math.Floor,但它只会将结果舍入到 4.00。以下是示例:
Math.Floor (41.75 * 0.1);
Math.Round(...)
函数有一个枚举值,决定使用哪种舍入策略。不幸的是,两种定义好的模式都不完全适合您的情况。
这两种中间值舍入模式为:
您想要使用的是使用一些乘法的Floor
函数。
var output = Math.Floor((41.75 * 0.1) * 100) / 100;
output
变量现在应该包含 4.17。
事实上,您也可以编写一个函数来接受变量长度:
public decimal RoundDown(decimal i, double decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(i * power) / power;
}
Math.Round方法(Decimal,Int32,MidpointRounding)
重载来解决问题(请参见https://dev59.com/IGYr5IYBdhLWcg3wn7kc)。 - Mat Mpublic double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
从.NET Core 3.0
开始和即将推出的.NET Framework 5.0
,以下是有效的。
Math.Round(41.75 * 0.1, 2, MidpointRounding.ToZero)
C# 中没有原生支持精度向下取整和向上取整的功能。
但是,您可以通过将数字乘以倍数、向下取整,然后再除以同样的倍数来模拟这个功能。
例如:
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
这不是最理想的解决方案,但如果数字较小,则应该可以工作。
public double RoundDownDouble(double number, int decimaPlaces)
{
var tmp = Math.Pow(10, decimaPlaces);
return Math.Truncate(number * tmp) / tmp;
}
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;
}
}
简单地说,Math.Round()
解决了这个问题,并且通过传递precision
参数和MidpointRounding
参数来适应情况。
简短的答案是:
Math.Round(41.75 * 0.1, 2, MidpointRounding.ToNegativeInfinity)
其中第二个参数是精度,第三个参数是舍入策略。
如果你想要了解Math.Round
的工作原理,你可以在这里阅读完整的解释:
如何在C#中将数字四舍五入到两位小数?
这是我的浮点数向下取整。
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);
}
}
/// <summary>
/// Truncates a Double to the given number of decimals without rounding
/// </summary>
/// <param name="D">The Double</param>
/// <param name="Precision">(optional) The number of Decimals</param>
/// <returns>The truncated number</returns>
public static double RoundDown(this double D, int Precision = 0)
{
if (Precision <= 0) return Math.Floor(D);
string S = D.ToString("0." + new string('0', Precision + 1));
return double.Parse(S.Substring(0, S.Length - 1));
}
Math.Round
吗? - nhahtdhMath.Round(41.75 * 0.1, 2, MidpointRounding.ToNegativeInfinity)
这将给你所需的精度下取整,第二个参数是精度,第三个参数是舍入策略。 - mahdi yousefi