我在 C# (VS 2008 SP1) 中看到了一种围绕货币的有趣情况。下面是测试用例的图片:
alt text http://img697.imageshack.us/img697/8500/testcases.png
我期望案例 5、6 和 7(我的错误是没有在输出中对它们进行编号)将数字四舍五入到一美分。
这是我的测试代码:
static void Main(string[] args)
{
decimal one = 10.994m;
decimal two = 10.995m;
decimal three = 1.009m;
decimal four = 0.0044m;
decimal five = 0.0045m;
decimal six = 0.0046m;
decimal seven = 0.0049m;
decimal eight = 0.0050m;
Console.WriteLine(one + ": " + one.ToString("C"));
Console.WriteLine(two + ": " + two.ToString("C"));
Console.WriteLine(three + ": " + three.ToString("C"));
Console.WriteLine(four + ": " + four.ToString("C"));
Console.WriteLine(five + ": " + five.ToString("C"));
Console.WriteLine(six + ": " + six.ToString("C"));
Console.WriteLine(seven + ": " + seven.ToString("C"));
Console.WriteLine(eight + ": " + eight.ToString("C"));
Console.ReadLine();
}
当我反射(reflect)到 .ToString(string format) 中以查看发生了什么时,我发现了
public string ToString(string format)
{
return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
调用
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string FormatDecimal(
decimal value,
string format,
NumberFormatInfo info);
该调用中是否有某种逻辑表明我当前的 NumberFormatInfo 区域性设置的粒度是货币的小数点后两位,所以不要让千分之十的数字上升,因为它无关紧要?
这个方法是如何实现的?我们是在位移位领域,还是在发生其他事情?
感谢任何见解。
最佳答案
根据基本的数学原理,案例 4、5、6 和 7 不应四舍五入到一分钱。您不会通过从最右边的数字开始并向上舍入来四舍五入。您只需查看要四舍五入的数字右侧的一位数。
http://www.enchantedlearning.com/math/rounding/
计算机只是在执行基本的数学运算,这是它们应该做的。
编辑 - 添加
关于C# 格式化货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588645/