Reputation: 170
I want to get the currency value in following format after doing 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
Thanks
Upvotes: 0
Views: 1253
Reputation: 9650
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.
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://learn.microsoft.com/en-us/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;
Console.WriteLine("{0:C0}", 99.556551);
Upvotes: 2