问题描述
查看msdn文档中的Convert.ToInt32()
,其中指出:
Looking at the msdn documentation for Convert.ToInt32()
it states:
http://msdn.microsoft.com/en-us/library/ffdk7eyz.aspx
这是为什么?
四舍五入到最接近的整数肯定是更合逻辑的,不是吗?如果是这样,则4.5将变为5,而5.5将变为6,这似乎更直观.
Surely it would be more logical to round to the nearest whole number, wouldn't it? If so, 4.5 would become 5, and 5.5 would become 6, which seems to be more intuitive.
推荐答案
如果您订阅该舍入机制,则只有更合乎逻辑".银行家四舍五入(在这种情况下,这是默认设置)也是完全合乎逻辑的.
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:
当然,这一切都可以追溯到财务日,并且可能会质疑其对整数的适用性,但是为什么要麻烦呢?接受它,如果需要,可以覆盖它,只是了解它是如何工作的.
对于想知道如何更改默认舍入的人:
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.
For people wondering how to change the default rounding:
如果要为Convert.ToInt32
提供非整数,则实际上首先需要执行类似Convert.ToDouble
的操作,然后执行 Math.Round
,带有重载以更改舍入逻辑.
If you are providing a non-integer to Convert.ToInt32
you will first actually need to do something like Convert.ToDouble
and then Math.Round
with the overload to change the rounding logic.
这篇关于为什么Convert.ToInt32()舍入到最接近的偶数,而不是最接近的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!