Converter -> public static int ToInt32(double value) 你用对了么?
Convert.ToInt32() 是我们经常使用的方法,但如果我们写如下的代码,能确定它的输出值么?
var x = 7.5;
Console.WriteLine(7.5 + ": " + Convert.ToInt32(x));
x = 6.5;
Console.WriteLine(6.5 + ": " + Convert.ToInt32(x));
让我意外的是,它的输出为:
7.5: 8
6.5: 6
有点疑惑,所以用Reflector看下了代码:
[__DynamicallyInvokable]
public static int ToInt32(double value)
{
if (value >= 0.0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 > 0.5) || ((num2 == 0.5) && ((num & ) != )))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & ) != )))
{
num3--;
}
return num3;
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
} 0x1[__DynamicallyInvokable]
public static int ToInt32(double value)
{
if (value >= 0.0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 > 0.5) || ((num2 == 0.5) && ((num & ) != )))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & ) != )))
{
num3--;
}
return num3;
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
6-15行的处理说明了问题,((num2 == 0.5) && ((num & 1) != 0) 判断如果是奇数,那么结果自增,否则不处理。Why? 为什么要这么处理? google了一下,发现.net的四舍五入都会使用“银行家四舍五入算法”:
The History section of the Wikipedia entry for Rounding has some statements about the role of "round to even" in computing. Interestingly, it appears "Bankers Rounding" has little evidence to state it was official in any sense of the word, so can only be chalked up as slang terminology.
It is only "more logical" if you subscribe to that rounding mechanism. Bankers rounding (which is the default in this case) is also perfectly logical.
Imagine if banks rounded up to the nearest penny for every fractional amount, they would make a lot less (lose a lot of, for the cynical) money with the millions upon millions of transactions that are processed daily. OK, so this example is cynical.
Going towards the nearest even number (or odd, but history chose otherwise) means that not every rounding resolution goes up, some can now go down. When you put this to the law of averages, it becomes a fair solution to use when considering who is responsible for paying for the extra half penny.
As for why this was chosen for the framework, this question attempts to address it:
Why does .NET use banker's rounding as default?
Of course, this all harks back to financial days and its applicability to integral numbers could be questioned, but why bother? Accept it, override it if you want to, just understand how it works.
请参阅:
http://stackoverflow.com/questions/11431793/convert-toint32-rounds-to-the-nearest-even-number
http://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default
Converter -> public static int ToInt32(double value) 你用对了么?的更多相关文章
- 【java】java.lang.Math:public static long round(double a)和public static int round(float a)
package math; public class TestMath_round { public static void main(String[] args) { System.out.prin ...
- Java——int、double型数组常用操作工具类
学了数组之后,感觉有好多操作需要经常去写,很不方便,因此自己做了一个工具类,方便调用,方法可能不全,希望大家可以添加,让我使用也方便一点儿. public class ArrayUtils { //求 ...
- 调用类java.lang.Math的成员方法"public static double random"运算下面表达式10000次,统计其中生成的整数0,1,2,.....20的个数分别是多少,并输出统计结果.(int)(Math.random()*20+0.5)
public class Test2 { public static void main(String args[]){ int num; int count[]=new int[21]; for(i ...
- c#的中英文混合字符串截取 public static string SubString(string inputString, int byteLength)
/// <summary> /// c#的中英文混合字符串截取(区分中英文) /// </summary> /// <param ...
- 大话java基础知识一之为什么java的主函数入口必须是public static void
为什么java的主函数入口必须是public static void main (String[] args); 很多写javaEE好几年的程序员经常会记得java的主函数就是这么写的,但实际上为什么 ...
- public static void main(String[] args){}函数诠释
public static void main(String[] args){}函数诠释 主函数的一般写法如下: public static void main(String[] args){-} 下 ...
- 《Java程序员面试笔试宝典》之为什么需要public static void main(String[] args)这个方法
public staticvoid main(String[] args)为Java程序的入口方法,JVM在运行程序的时候,会首先查找main方法.其中,public是权限修饰符,表明任何类或对象都可 ...
- 【java】计算一段代码执行时长java.lang.System类里的public static long currentTimeMillis()方法
public class Test_currentTimeMillis { public static void main(String[] args) { long start=System.cur ...
- 主函数特别之处:public static void main(String[] args)
public static void main(String[] args) public class Test_java {//主函数特殊之处 public static void main(Str ...
随机推荐
- AC日记——魔法森林 洛谷 P2387
魔法森林 思路: spfa水过(正解lct); 代码: #include <bits/stdc++.h> using namespace std; #define maxn 50005 # ...
- 五十八 数据库访问使用SQLite
SQLite是一种嵌入式数据库,它的数据库就是一个文件.由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成. Python就 ...
- 从TS流定位H264的每一个视频帧开始,判断出帧类型
从TS流定位H264的每一个视频帧开始,判断出帧类型(待续)
- Python开发基础-Day19继承组合应用、对象序列化和反序列化,选课系统综合示例
继承+组合应用示例 class Date: #定义时间类,包含姓名.年.月.日,用于返回生日 def __init__(self,name,year,mon,day): self.name = nam ...
- [P3806] Divide and Conquer on Tree
Link: P3806 传送门 Solution: 询问树上是否存在两点间的距离为$k$,共有$m$次询问($m\le 100,k\le 1e7$) 预处理出所有距离的可能性再$O(1)$出解的复杂度 ...
- Java学习笔记(8)
static修饰方法(静态的成员方法): 访问方式: 可以使用对象进行访问 对象.静态函数名(): 可以使用类名进行访问 类名. ...
- [bzoj1008](HNOI2008)越狱(矩阵快速幂加速递推)
Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生越狱,求有多少种状态可能发生越狱 In ...
- sql 空值设置默认值
ifnull(a.discountsign, ') AS "discountsign"
- .net设置中GridView自适应列宽
有一个项目只有30分钟开发时间,速成,使用了古老的.net gridview. 但需要列宽自适应好看些. 于是琢磨了,实现思路如下. 先看下大致效果(很粗暴没有优化) 代码如下: protected ...
- 从co到koa01-co
thunk 他的发展是由函数的求值策略的分歧决定的,两种求值策略 传值调用,在进入函数体之前就直接执行完,把值传进去 传名调用,将表达式传入函数体,只在用到他的时候求值 传名函数的编译器实现,其实就是 ...