简体   繁体   中英

String format C#

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

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://docs.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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM