C#四舍五入用法实例
作者:jjt 时间:2021-07-20 02:49:20
C# 中没有四舍五入函数,程序语言都没有四舍五入函数,因为四舍五入算法不科学,国际通行的是 Banker 舍入法
Bankers rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的。
Math.Round 方法默认的也是 Banker 舍入法
在 .NET 2.0 中 Math.Round 方法有几个重载方法
Math.Round(Decimal, MidpointRounding)
Math.Round(Double, MidpointRounding)
Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Double, Int32, MidpointRounding)
将小数值舍入到指定精度。MidpointRounding 参数,指定当一个值正好处于另两个数中间时如何舍入这个值
该参数是个 MidpointRounding 枚举
此枚举有两个成员,MSDN 中的说明是:
AwayFromZero 当一个数字是其他两个数字的中间值时,会将其舍入为两个值中绝对值较小的值。
ToEven 当一个数字是其他两个数字的中间值时,会将其舍入为最接近的偶数。
注 意!这里关于 MidpointRounding.AwayFromZero 的说明是错误的!实际舍入为两个值中绝对值较大的值。不过 MSDN 中的 例子是正确的,英文描述原文是 it is rounded toward the nearest number that is away from zero.
所以,要实现四舍五入函数,对于正数,可以加一个 MidpointRounding.AwayFromZero 参数指定当一个数字是其他两个数字的中间值时其舍入为两个值中绝对值较大的值,例:
Math.Round(3.45, 2, MidpointRounding.AwayFromZero)
不过对于负数上面的方法就又不对了
因此需要自己写个函数来处理
第一个函数:
double Round(double value, int decimals)
{
if (value < 0)
{
return Math.Round(value + 5 / Math.Pow(10, decimals + 1), decimals, MidpointRounding.AwayFromZero);
}
else
{
return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
}
}
第二个函数:
double Round(double d, int i)
{
if(d >=0)
{
d += 5 * Math.Pow(10, -(i + 1));
}
else
{
d += -5 * Math.Pow(10, -(i + 1));
}
string str = d.ToString();
string[] strs = str.Split('.');
int idot = str.IndexOf('.');
string prestr = strs[0];
string poststr = strs[1];
if(poststr.Length > i)
{
poststr = str.Substring(idot + 1, i);
}
string strd = prestr + "." + poststr;
d = Double.Parse(strd);
return d;
}
参数:d表示要四舍五入的数;i表示要保留的小数点后为数。
其中第二种方法是正负数都四舍五入,第一种方法是正数四舍五入,负数是五舍六入。
备注:个人认为第一种方法适合处理货币计算,而第二种方法适合数据统计的显示。
来源:http://www.cnblogs.com/jjt0624033/archive/2011/06/30/2094735.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
WPF在VisualTree上增加Visual
![](https://img.aspxhome.com/file/2023/3/88423_0s.png)
SpringBoot整合java诊断工具Arthas解读
![](https://img.aspxhome.com/file/2023/0/69920_0s.png)
SpringBoot文件访问映射如何实现
Java注解与反射原理说明
详解SpringBoot项目的创建与单元测试
![](https://img.aspxhome.com/file/2023/2/65152_0s.png)
Android实现带指示器的自动轮播式ViewPager
![](https://img.aspxhome.com/file/2023/2/97852_0s.gif)
Javaweb动态开发最重要的Servlet详解
![](https://img.aspxhome.com/file/2023/4/84274_0s.png)
Java超详细分析@Autowired原理
![](https://img.aspxhome.com/file/2023/9/60059_0s.png)
Spring Boot 整合mybatis 使用多数据源的实现方法
![](https://img.aspxhome.com/file/2023/0/99920_0s.png)
Android Jetpack组件中LifeCycle作用详细介绍
![](https://img.aspxhome.com/file/2023/2/89542_0s.png)
详解Java的Hibernat框架中的Map映射与SortedMap映射
C#泛型约束的深入理解
IntelliJ IDEA 安装教程2019.09.23(最新版)
![](https://img.aspxhome.com/file/2023/5/58175_0s.jpg)
c#构造初始化的顺序浅析
java实现ftp上传 如何创建文件夹
DevExpress获取TreeList可视区域节点集合的实现方法
java利用mybatis拦截器统计sql执行时间示例
eclipse的git插件安装、配置与使用详解
![](https://img.aspxhome.com/file/2023/7/89957_0s.png)
用intellij Idea加载eclipse的maven项目全流程(图文)
![](https://img.aspxhome.com/file/2023/2/60082_0s.jpg)
ReentrantLock源码详解--条件锁
![](https://img.aspxhome.com/file/2023/8/69108_0s.png)