Reputation: 950
Is there any way to format a number in the currency format (in the current Culture) using a custom format string?
For example:
1525.00 -> $1,525 (no trailing zeros)
1525.25 -> $1,525.25 (show decimals only when necessary)
We have tried different formats but none of them can produce the above.
Upvotes: 1
Views: 539
Reputation: 34947
Does this count?
static string MyCustomCurrencyString(decimal d) => d % 1 == 0 ? $"{d:C0}" : $"{d:C2}";
Let's test it:
Console.WriteLine(ZerosAreBad(1525));
Console.WriteLine(ZerosAreBad(1525.25m));
It works!
$1,525
$1,525.25
Upvotes: 2
Reputation: 98740
As far as I know, no, you can't do that with a "one" format since you don't want show decimal parts for the first one but you "want" to show decimals part for the second one. I don't think there will be a "simple" format for both.
You can check the Currency format specifier (C)
for that as;
var v = 1525.00;
$"{v:C0}".Dump();
returns $1,525
and
var v = 1525.25;
$"{v:C2}".Dump();
return $1,525.25
.
Just a note, string interpolation uses CurrentCulture
settings and in that case, I assume your current culture is somewhat based on english-based or InvariantCulture
for generate CurrencySymbol
, NumberGroupSeparator
and NumberDecimalSeparator
as $
, ,
and .
respectively.
Upvotes: 2