在c#中向下舍入到2位小数
如何将两位小数相乘并将结果四舍五入到小数点后两位?
例如,如果方程为41.75 x 0.1,则结果为4.175。 如果我在带小数的c#中执行此操作,它将自动舍入到4.18。 我想四舍五入到4.17。
我尝试使用Math.Floor,但它只是向下舍入到4.00。 这是一个例子:
Math.Floor (41.75 * 0.1);
Math.Round(...)
函数有一个Enum来告诉它使用什么舍入策略。 不幸的是,这两个定义并不完全符合您的情况。
两个中点舍入模式是:
- AwayFromZero – 当一个数字介于另外两个数字之间时,它会向最接近零的数字四舍五入。 (阿卡,向上)
- ToEven – 当一个数字介于另外两个数字之间时,它会向最接近的偶数舍入。 (将赞成.16超过.17,和.18超过.17)
您想要使用的是具有一些乘法的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; }
public double RoundDown(double number, int decimalPlaces) { return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces); }
c#中没有精密地板/毛细管的原生支持。
但是,您可以通过将数字乘以楼层来模拟function,然后除以相同的乘数。
例如,
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
不是理想的解决方案,但如果数量很小则应该有效。
另一种解决方案是从零舍入到零而舍入为零。 它应该是这样的:
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; } }