C# 双格式问题
我正在使用下一个代码来格式化双精度值:
String.Format("${0:0,0.#}",...);
它工作得很好,但是当数字小于 10 时,我遇到了问题。例如,数字显示为 $03、$06。
请告诉我正确的字符串,使其具有下一个格式的双数 ddd,ddd,ddd,ddd.dd
I am using next code to format double value:
String.Format("${0:0,0.#}",...);
It working great, but when numbers are less than 10, I got problem. Numbers are displayed as $03, $06 for example.
Please advise me correct string to have a double number in next format ddd,ddd,ddd,ddd.dd
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请尝试以下操作:
如果您的双精度代表您应该使用的货币:
请注意,如果您省略
CultureInfo.InvariantCulture
,它可能会在某些计算机上使用$
以外的其他内容显示。例如,在我的计算机上string.Format("{0:c}", d)
给出2,00 kr
这可能不是您想要的。在您的示例中,您实际上根本不需要使用
string.Format
。你可以用它来代替:除了更清晰、更简洁之外,它还有避免装箱的优点。当然,如果您的格式字符串比示例中的更复杂,那么使用
string.Format
是有意义的。作为最后的评论,我建议不要使用双精度数来存储货币。小数类型可能更合适。
Try this instead:
If your double represents a currency you should use:
Note that if you omit the
CultureInfo.InvariantCulture
it could display using something other than$
on some computers. For example on my computerstring.Format("{0:c}", d)
gives2,00 kr
which might not be what you wanted.In your example you don't actually need to use
string.Format
at all. You could use this instead:As well as being clearer and more concise, it also has the advantage of avoiding boxing. Of course if your format string is more complex than in your example then it would make sense to use
string.Format
.And as a final remark I'd recommend against using doubles to store currency. A decimal type is probably more appropriate.
使用货币格式:
Use currency formatting:
或者
myDecimal.ToString("C");
将显示到小数点后两位,包括逗号分隔符并包括美元符号(基于区域性设置)。如果您希望它保留 1 位或 2 位以上小数,请在 C 后添加一个数字(即 C3)
or
myDecimal.ToString("C");
will display to two decimal places, include the comma separator and include the dollar sign (based on culture settings) in one fell swoop. If you want it to go to 1 or more than 2 decimal places, include a number after the C (i.e. C3)
应该这样做。
请参阅自定义数字格式字符串
should do it.
See Custom Numeric Format Strings