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:定向向零舍入的策略,结果最接近且数量级不大于无限精确结果。

示例代码

MathRoundTestDemo.cs

posted @ 2022-10-23 16:39  Lulus  阅读(597)  评论(0编辑  收藏  举报