.NET货币格式化程序:我可以指定银行家舍入的使用吗?
-
02-07-2019 - |
解决方案
你不能简单地在字符串输入上调用Math.Round()来获得你想要的行为吗?
而不是:
string s = string.Format("{0:c}", 12345.6789);
执行:
string s = string.Format("{0:c}", Math.Round(12345.6789));
其他提示
Regexp是一种模式匹配语言。你不能在Regexp中进行算术运算。
使用IFormatProvider和ICustomFormatter进行一些实验。这是一个链接可能会指向正确的方向。 http://codebetter.com/blogs/david。海登/存档/ 2006/03/12 / 140732.aspx
它不可能,正则表达式没有任何“数字”的概念。您可以使用匹配评估者但是你要添加命令式的c#代码,并且会偏离你的正则表达式的唯一要求。
.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();
不隶属于 StackOverflow