C#格式化货币

blu*_*blu 3 c# formatting rounding

我看到一个有趣的情况围绕C#(VS 2008 SP1)中的货币.下面是测试用例的图像:

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();
}
Run Code Online (Sandbox Code Playgroud)

当我反思.ToString(字符串格式),看看我发现了什么

public string ToString(string format)
{
    return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
Run Code Online (Sandbox Code Playgroud)

有呼吁

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string FormatDecimal(
    decimal value, 
    string format, 
    NumberFormatInfo info);
Run Code Online (Sandbox Code Playgroud)

在那个调用中是否有一些逻辑说我的当前文化设置的NumberFormatInfo的粒度是当前的两位小数,所以不要让千分之一的位置滚动数字,因为它是无关紧要的?

这个方法是如何实现的?我们是在转移土地,还是其他事情发生?

感谢您的任何见解.

Dav*_*vid 8

遵循基本的数学原理,案例4,5,6和7不应该是一分钱.从最右边的数字开始并向上舍入,你不会舍入.您只需查看要舍入的数字右侧的一位数.

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

计算机正在执行基本的数学运算.

编辑 - 添加

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