.NET 货币格式化程序:我可以指定使用银行四舍五入吗?
有谁知道如何获取格式字符串来使用 银行家舍入 ? 我一直在使用“{0:c}”,但这与银行四舍五入的方式不同。 Math.Round()
< /a> 方法进行银行四舍五入。 我只需要能够使用格式字符串复制它的舍入方式。
注意:最初的问题相当具有误导性,提及正则表达式的答案由此而来。
Does anyone know how I can get a format string to use bankers rounding? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The Math.Round()
method does bankers rounding. I just need to be able to duplicate how it rounds using a format string.
Note: the original question was rather misleading, and answers mentioning regex derive from that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
难道您不能简单地在字符串输入上调用 Math.Round() 来获得您想要的行为吗?
而不是:
做:
Can't you simply call Math.Round() on the string input to get the behavior you want?
Instead of:
Do:
Regexp 是一种模式匹配语言。 您不能在 Regexp 中进行算术运算。使用 IFormatProvider 和 ICustomFormatter 进行一些实验。 这里的链接可能会为您指明正确的方向。 http://codebetter.com/blogs/david。海登/archive/2006/03/12/140732.aspx
Regexp is a pattern matching language. You can't do arithmetic operations in Regexp.Do some experiements with IFormatProvider and ICustomFormatter. Here is a link might point you in the right direction. http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx
这是不可能的,正则表达式没有任何“数字”的概念。 您可以使用匹配评估器< /a> 但您将添加命令式 C# 代码,并且会偏离您仅正则表达式的要求。
Its not possible, a regular expression doesn't have any concept of "numbers". You could use a match evaluator but you'd be adding imperative c# code, and would stray from your regex only requirement.
.Net 内置了对算术舍入和银行家舍入的支持:
“偶数”舍入实际上是默认设置,尽管“远离零”是您在学校学到的。
这是因为计算机处理器在幕后也进行银行家的四舍五入。
我本以为任何舍入格式字符串都会默认为银行舍入,不是这样吗?
.Net has built in support for both Arithmetic and Bankers' rounding:
"To even" rounding is actually the default, even though "away from zero" is what you learnt at school.
This is because under the hood computer processors also do bankers' rounding.
I would have thought that any rounding format string would default to bankers' rounding, is this not the case?
如果您使用的是.NET 3.5,您可以定义一个扩展方法来帮助您执行此操作:
然后,当您调用它时,您可以执行以下操作:
If you are using .NET 3.5, you can define an extension method to help you do this:
Then, when you call it, you can do: