.NET货币格式化程序:我可以指定使用银行取整吗?

时间:2020-03-06 14:40:32  来源:igfitidea点击:

有谁知道我如何获得格式字符串以使用银行取整?我一直在使用" {0:c}",但这与银行家四舍五入的方式不同。 " Math.Round()"方法可以对银行家进行四舍五入。我只需要能够使用格式字符串复制它的舍入方式。

注意:最初的问题颇具误导性,因此提及正则表达式的答案也由此产生。

解决方案

正则表达式是一种模式匹配语言。我们无法在Regexp中执行算术运算。

用IFormatProvider和ICustomFormatter做一些实验。这里的链接可能会为我们指明正确的方向。 http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx

这是不可能的,正则表达式没有"数字"的任何概念。我们可以使用匹配评估器,但是我们将添加命令式Ccode,这将偏离我们仅使用正则表达式的要求。

我们不能简单地在字符串输入上调用Math.Round()以获得所需的行为吗?

代替:

string s = string.Format("{0:c}", 12345.6789);

做:

string s = string.Format("{0:c}", Math.Round(12345.6789));

.Net内置了对算术和银行家舍入的支持:

//midpoint always goes 'up': 2.5 -> 3
Math.Round( input, MidpointRounding.AwayFromZero );

//midpoint always goes to nearest even: 2.5 -> 2, 5.5 -> 6
//aka bankers' rounding
Math.Round( input, MidpointRounding.ToEven );

实际上,即使我们在学校学到的是"远离零","四舍五入"舍入实际上也是默认值。

这是因为在后台,计算机处理器还会进行银行家的四舍五入。

//defaults to banker's
Math.Round( input );

我本以为任何舍入格式字符串都将默认为银行家的舍入,不是这种情况吗?

如果使用的是.NET 3.5,则可以定义扩展方法来完成以下操作:

public static class DoubleExtensions
{
    public static string Format(this double d)
    {
        return String.Format("{0:c}", Math.Round(d));
    }
}

然后,当我们调用它时,我们可以执行以下操作:

12345.6789.Format();