C# 保留n位小数的问题
我们在计算数字时,有时会需要保留几位小数,有时需要四舍五入,有时候需要直接舍弃后面的小数,有时候需要进一位,其实C#的Math.Round()
方法有提供相应的选项,即MidpointRounding
。
我们翻阅Math.Round Method可以看到,Math.Round()
有多参数重载。
其中Math.Round(Decimal, Int32, MidpointRounding)
支持保留n位小数,并且选择四舍五入的策略。
下面是例子代码
var originalNumber = (decimal)9.081;
var nomalNumber = Math.Round(originalNumber, 2);//output:9.08
var toEvenNumber = Math.Round(originalNumber, 2, MidpointRounding.ToEven);//output:9.08
var awayFromZeroNumber = Math.Round(originalNumber, 2, MidpointRounding.AwayFromZero);//output:9.08
var toZeroNumber = Math.Round(originalNumber, 2, MidpointRounding.ToZero);//output:9.08
var toNegativeInfinityNumber = Math.Round(originalNumber, 2, MidpointRounding.ToNegativeInfinity);//output:9.08
var toPositiveInfinityNumber = Math.Round(originalNumber, 2, MidpointRounding.ToPositiveInfinity);//output:9.09
var originalNumber2 = (decimal)9.087;
var nomalNumber2 = Math.Round(originalNumber2, 2);//output:9.09
var toEvenNumber2 = Math.Round(originalNumber2, 2, MidpointRounding.ToEven);//output:9.09
var awayFromZeroNumber2 = Math.Round(originalNumber2, 2, MidpointRounding.AwayFromZero);//output:9.09
var toZeroNumber2 = Math.Round(originalNumber2, 2, MidpointRounding.ToZero);//output:9.08
var toNegativeInfinityNumber2 = Math.Round(originalNumber2, 2, MidpointRounding.ToNegativeInfinity);//output:9.08
var toPositiveInfinityNumber2 = Math.Round(originalNumber2, 2, MidpointRounding.ToPositiveInfinity);//output:9.09
var originalNumber3 = (decimal)9.085;
var nomalNumber3 = Math.Round(originalNumber3, 2);//output:9.08
var toEvenNumber3 = Math.Round(originalNumber3, 2, MidpointRounding.ToEven);//output:9.08
var awayFromZeroNumber3 = Math.Round(originalNumber3, 2, MidpointRounding.AwayFromZero);//output:9.09
var toZeroNumber3 = Math.Round(originalNumber3, 2, MidpointRounding.ToZero);//output:9.08
var toNegativeInfinityNumber3 = Math.Round(originalNumber3, 2, MidpointRounding.ToNegativeInfinity);//output:9.08
var toPositiveInfinityNumber3 = Math.Round(originalNumber3, 2, MidpointRounding.ToPositiveInfinity);//output:9.09
在MidpointRounding Enum中,我们可以看到每一种枚举值的策略。
AwayFromZero:舍入到最接近的数字的策略,当数字在两个数字之间的中间时,它将舍入到离零的最接近的数字。
ToEven:舍入到最接近的数字的策略,当数字在两个数字之间的中间时,它将舍入到最接近的偶数。
ToNegativeInfinity:向下定向舍入的策略,结果最接近且不大于无限精确结果。
ToPositiveInfinity:向上定向舍入的策略,结果最接近且不小于无限精确结果。
ToZero:定向向零舍入的策略,结果最接近且数量级不大于无限精确结果。
示例代码
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。