C#格式化货币

时间:2010-04-06 21:57:14

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

当我反映到.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文化设置的粒度是当前的两位小数,所以不要让千分之一的位置滚动数字,因为它是无关紧要的?

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

感谢您的任何见解。

1 个答案:

答案 0 :(得分:8)

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

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

计算机只是执行基本数学,因为它们应该如此。

修改 - 添加

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