C# 格式化货币

标签 c# formatting rounding

我在 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/

计算机只是在执行基本的数学运算,这是它们应该做的。

编辑 - 添加

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

关于C# 格式化货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588645/

相关文章:

c# - 如何在 C# 中动态调用具有任意签名的方法?

html - 如何在grails中将g:textArea的内容设置为HTML(格式化文本,而非代码)

c - 需要更好的方法来格式化 C 中的电话号码

excel - 如何让excel显示一定数量的有效数字?

c# - MongoDB - 使用 C# 驱动程序按日期和时间搜索

c# - 如何在 Xamarin.Forms 中定义两个可相互更新的可绑定(bind)属性?

c# - TryReset CancellationSource .NET 标准

reporting-services - 在 SSRS 2008 中获取表格范围之外的表格行数

c++ - 从格式为 %.1f 的 printf 中查找舍入数字的意外错误?

javascript - 在javascript中对数字进行四舍五入