我感兴趣的是如何将变量四舍五入到小数点后两位。在下面的示例中,奖金通常是一个有四个小数位的数字。有没有办法确保pay变量总是四舍五入到小数点后两位?
pay = 200 + bonus;
Console.WriteLine(pay);发布于 2012-09-27 20:41:59
使用Math.Round并指定小数位数。
Math.Round(pay,2);Math.Round Method (Double, Int32)
将双精度浮点值舍入到指定的小数位数。
或Math.Round Method (Decimal, Int32)
将十进制值四舍五入到指定的小数位数。
发布于 2012-09-27 20:46:51
您应该使用Math.Round的一种形式。请注意,除非您指定MidpointRounding值,否则Math.Round默认为银行家舍入(舍入到最接近的偶数)。如果你不想使用四舍五入,你应该使用Math.Round(decimal d, int decimals, MidpointRounding mode),如下所示:
Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven); // .005 rounds to nearest even (0.00)
Math.Round(pay, 2); // Defaults to MidpointRounding.ToEven发布于 2012-09-27 20:43:02
decimal pay = 1.994444M;
Math.Round(pay , 2); https://stackoverflow.com/questions/12621640
复制相似问题