需要自定义货币格式才能与 String.Format 一起使用
我正在尝试在 C# 中使用 String.Format("{0:c}", somevalue) 但很难弄清楚如何配置输出以满足我的需求。 这是我的需求:
- 0 输出到空白
- 1.00 输出到 $1.00
- 10.00 输出到 $10.00
- 100.00 输出到 $100.00
- 1000.00 输出到 $1,000.00
我尝试过 String.Format("{0:c}", somevalue) 但对于零值,它输出 $0.00这不是我想要的。 我也尝试过 String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue),但对于 1.0 它输出 $01.00。 String.Format("{0:$0.00;$(0.00);#}", somevalue) 适用于大多数情况,但当 somevalue 为 1000.00 时,输出为 $1000.00。
是否有某种格式可以满足上述所有 5 种情况? 我读过的所有文档都只详细介绍了基础知识,并没有涉及这种类型的场景。
I'm trying to use String.Format("{0:c}", somevalue) in C# but am having a hard time figuring out how to configure the output to meet my needs. Here are my needs:
- 0 outputs to blank
- 1.00 outputs to $1.00
- 10.00 outputs to $10.00
- 100.00 outputs to $100.00
- 1000.00 outputs to $1,000.00
I've tried String.Format("{0:c}", somevalue) but for zero values it outputs $0.00 which is not what I want. I've also tried String.Format("{0:$0,0.00;$(0,0.00);#}", somevalue), but for 1.0 it outputs $01.00. String.Format("{0:$0.00;$(0.00);#}", somevalue) works for most cases, but when somevalue is 1000.00 the output is $1000.00.
Is there some format that will fit all 5 cases above? All of the documentation I've read only details the basics and doesn't touch on this type of scenario.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用
零值,您将得到“”,其他值也应正确格式化。
If you use
You will get "" for the zero value and the other values should be formatted properly too.
尝试这样的事情:
Try something like this:
根据您是否始终对所有货币值使用相同的数据类型,您可以编写一个扩展方法,以便始终满足您的情况。 例如,如果您使用十进制类型:
Depending on if you are consistently using the same data type for all of your currency values, you could write an extension method that would make it so that your case is always met. For example if you were using the decimal type:
这里是您的一个很好的参考可能有用,它总结了这些数据: http://blog.stevex.net/ csharp 中的字符串格式/
Here's a great reference that you might find useful, which summarises this data: http://blog.stevex.net/string-formatting-in-csharp/
“C”货币格式非常有用,直到您需要 0 的空白为止。这里有两种方法,一种是上面提到的,类似于我使用的为 0 提供空白的方法:
第二种技术感觉更“流畅”,如果你喜欢那种代码风格(就像我一样)。
The "C" currency formats are great until you need a blank for 0. Here are two ways, one mentioned above, similar to the ones that I use that give you the blank for 0:
The second technique feels more "fluent", if you like that style of code (as I do).