2010-04-06 211 views
3

我在C#(VS 2008 SP1)中看到了一个有趣的情况。下面是测试案例的图像:C#格式货币

alt text http://img697.imageshack.us/img697/8500/testcases.png

我所期待的情况下,五,六,七(我坏在输出未编号它们)圆人数达一分钱。

这里是我的测试代码:

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(); 
} 

当我反映到的ToString(字符串格式),看看发生了什么事情,我发现

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文化设置的粒度小数点后两位小数,所以不要让万分之一的数字上升,因为它是微不足道的?

该方法是如何实现的?我们是否正在转移土地,还是有其他的事情呢?

感谢您的任何见解。

+0

如果你真的想病例5,6,7围捕一分钱,那么你需要第一轮的一半一分钱: Math.Round(五,三,MidpointRounding.AwayFromZero):结果会变成一分钱。 – 2010-04-06 22:22:24

+0

找到衡量毫克币的文化,你会得到平反。 – 2010-04-06 22:24:11

+1

“啊,不,你不明白,它非常复杂,它是聚合的,所以我在这里谈论的是一分钱,随着时间的推移,它们会增加很多。” http://www.harp.com/title/tt0151804/quotes?qt0996772 – blu 2010-04-07 02:14:19

回答

8

遵循基本的数学原理,案例4,5,6和7不应该花费一分钱。你不会从最右边的数字开始并四舍五入。你只看到你想要的数字右边的一个数字。

http://www.enchantedlearning.com/math/rounding/

计算机只是进行基本的数学,因为他们应该。

编辑 - 添加

更好的链路: http://math.about.com/od/arithmetic/a/Rounding.htm

+0

有趣,那么案例1呢? – blu 2010-04-06 22:05:30

+0

在情况1中,最后一位数字将强制最后9个四舍五入。因为9 + 1 = 10,那么接下来的9就必须加1,因为这是9 ... – David 2010-04-06 22:06:42

+0

好的,所以我们说我们正在四舍五入到百分之一的位置,所以只看数字直接向右。好的,很好的答案,谢谢。 – blu 2010-04-06 22:09:37