如何在“#,##0”之间转换 和“{0:n2}” 样式格式字符串表示形式?
.NET 支持两种类型的字符串格式。
我所处的情况是现有配置数据具有 #,##0
样式格式。 新功能需要格式化为相同的输出,但此功能所需的 API 仅接受 {0:n2}
类型的格式。
有谁知道在这两种数字类型表示之间进行转换的方法? DateTime
可以忽略。
编辑我了解到:
.NET supports two types of string formatting.
I'm in a situation where existing configuration data has #,##0
style formatting. A new feature requires formatting to the same output, but the API needed for this feature only accepts formatting of type {0:n2}
.
Does anyone know of a means to convert between these two representations for numeric types? DateTime
can be ignored.
EDIT I've learned that:
The
{0:n2}
style is known as standard numeric formattingThe
#,##0
style is known as custom numeric formatting
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你不能。
从有关标准格式的 MSDN 文章的链接 字符串,你会发现:
因此,标准格式说明符将根据程序运行的区域性而变化。
由于您的自定义格式准确地指定了数字的外观,无论程序在哪种文化下运行。 它看起来总是一样的。
程序运行时的区域性在编译时是未知的,它是一个运行时属性。
所以答案是:不,你不能自动映射,因为不存在一对一一致的映射。
No, you can't.
From your link to the MSDN articles about standard format strings, you'll find:
So the standard formatting specifiers will vary depending on which culture the program is running under.
Since your custom formating specifies exactly how the number is going to look, whatever the culture the program is running under. Its allways gonna look the same.
The culture the program is running under isn't known during compile time, it's a runtime property.
So the answer is: No, you can't map automatically, because there isn't a one-to-one consistent mapping.
黑客警报!!!
如Arjan在他的出色回答中指出我想要做的事情在所有语言环境中都不可能以防弹方式实现(感谢Arjan)。
就我的目的而言,我知道我只处理数字,而我关心的主要问题是小数位数相同。 这是我的技巧。
HACK ALERT!!!
As Arjan pointed out in his excellent answer what I want to do isn't possible in a bullet proof fashion across all locales (Thanks Arjan).
For my purposes, I know I'm only dealing with numbers and the major thing I'm concerned with is having the same number of decimal places. So here's my hack.
这用于将数字格式化为小数点后两位
This used for formatting number into 2 decimal places