C#中Math.Round四舍五入的用法详解,

本文详细解析了C#中的Math.Round方法,并说明其遵循的五舍六入规则而非传统意义上的四舍五入。通过具体示例展示了如何利用MidpointRounding.AwayFromZero属性实现常规的四舍五入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于C#里面的Math.Round,很多人都会用到,而且以为是四舍五入,其实不是这样的:

C#里面的Math.Round是符合IEEE标准的“四舍五入”,其实是五舍六入。看下面测试:

            double testd = 3184.39995117187;
            double nd = Math.Round(testd, 2);   // 3184.4
            nd = Math.Round(testd, 2, MidpointRounding.AwayFromZero);// 3184.4


            nd = Math.Round(3184.367, 2);    //  3184.37
            nd = Math.Round(3184.365, 2);    // 3184.36


            nd = Math.Round(3184.367, 2, MidpointRounding.AwayFromZero);   //3184.37
            nd = Math.Round(3184.365, 2, MidpointRounding.AwayFromZero);    //3184.37   
如果想变成我们理解的四舍五入,使用这个属性即可。
MidpointRounding.AwayFromZero



                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值