如何舍入小数?

给定十进制’96 .154’,我怎样才能确保它总是向上舍入到96.16(而不是正常舍入到2位小数,这将给出96.15)。

有点hacky,但这是一种非常直观的方式:

var val = 96.154M; var result = Math.Ceiling(val * 100) / 100.0M; 

您可以将0.005添加到值,然后舍入结果。

我认为你正在寻找Math.Ceiling方法。

您可以将其与乘数组合以指定要舍入的小数位数。 像这样,

 public float roundUp(float number, int numDecimalPlaces) { double multiplier = Math.Pow(10, numDecimalPlaces)) return Math.ceiling(number*multiplier) / multiplier; } 

以下是值和基本分数的roundUp方法的代码。 您应该用于问题的基本分数是0.05M。 然而,该方法可用于其他常见场景,即基础分数0.5M; 并且您可以以有趣的方式应用它,例如使用0.3M的基本分数。 好吧,我希望它能回答你的问题,玩得开心:

 static decimal roundUp(decimal aValue, decimal aBaseFraction) { decimal quotient = aValue / aBaseFraction; decimal roundedQuotient = Math.Round(quotient, 0); decimal roundAdjust = 0.0M; if (quotient > roundedQuotient) { roundAdjust = aBaseFraction; } return roundAdjust + roundedQuotient * aBaseFraction; } 

这是我的RoundUp方法版本,在此可以是特定的小数

 void Main() { Console.WriteLine(RoundUp(2.8448M, 2)); //RoundUp(2.8448M, 2).Dump(); } public static decimal RoundUp(decimal numero, int numDecimales) { decimal valorbase = Convert.ToDecimal(Math.Pow(10, numDecimales)); decimal resultado = Decimal.Round(numero * 1.00000000M, numDecimales + 1, MidpointRounding.AwayFromZero) * valorbase; decimal valorResiduo = 10M * (resultado - Decimal.Truncate(resultado)); if (valorResiduo < 5) { return Decimal.Round(numero * 1.00M, numDecimales, MidpointRounding.AwayFromZero); } else { var ajuste = Convert.ToDecimal(Math.Pow(10, -(numDecimales + 1))); numero += ajuste; return Decimal.Round(numero * 1.00000000M, numDecimales, MidpointRounding.AwayFromZero); } }