[英]String format C#
I want to get the currency value in following format after doing string.format. 我想在执行string.format之后以以下格式获取货币值。 I have used several formats but none of them are like what i wanted.
我使用了几种格式,但是没有一种格式符合我的要求。
Value After Format
0 $0
123 $123
1234 $1,234
12345 $12,345
I have used following code and it works fine. 我使用了以下代码,它工作正常。
Console.WriteLine(string.Format("{00:$#,#}", 12345));
But the problem is that when value becomes 0 then it prints just $
whereas i want to print $0
但问题是,当值变为0时,它只打印
$
而我要打印$0
Thanks 谢谢
The # in the format string means display a digit if it is not zero. 格式字符串中的#表示如果不为零,则显示一个数字。 So when you have a 0 value, then it will not display anything.
因此,当您的值为0时,它将不会显示任何内容。
So you need to change this to 因此,您需要将其更改为
Console.WriteLine(string.Format("{00:$#,0}", mynumber));
But you can also use the inbuilt currency string formatting option. 但是,您也可以使用内置货币字符串格式设置选项。
The docs have a whole section on currency formatting https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#CFormatString 该文档整节介绍了货币格式https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/standard-numeric-format-strings#CFormatString
So then you can have 这样你就可以
Console.WriteLine(string.Format("{0:c}", 99.556551));
Or if you don't want any decimals places then 或者,如果您不希望小数位
Console.WriteLine(string.Format("{0:C0}", 99.556551));
Although this will round the value as well, so it might be better if you control this yourself. 尽管这也会使值取整,但是如果您自己控制它可能会更好。
And as reminded by @RufusL below, the string.format
is not needed in a Console.Writeline,
so you can also simplify this further; 就像下面的@RufusL所提醒的那样,在
Console.Writeline,
不需要string.format
Console.Writeline,
因此您还可以进一步简化它。
Console.WriteLine("{0:C0}", 99.556551);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.