0

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

3
  • Did you try 00:$#,0 ? Commented Nov 7, 2017 at 9:03
  • Did you try Console.WriteLine(string.Format("{00:$0,#}", 12345)); Commented Nov 7, 2017 at 9:03
  • Just to mention it: learn.microsoft.com/en-us/dotnet/standard/base-types/… You can even have positive, zero and negative values be formatted differently in one format expression. Commented Nov 7, 2017 at 9:26

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@RufusL Yes of course you are right, I just focused on the formatting differences and copy and pasted the rest and I and neglected this. I will update to make this obvious.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.