Format a string to a currency with negative currency like $(10.00)
-
03-06-2021 - |
Question
I need to format a negative currency as follow: $(10.00)
I tried to use string.Format("{0:C}", itemprice)
but that gives me this result ($10.00)
(the $ inside the parenthesis
i also tried
string fmt = "##;(##)";
itemprice.ToString(fmt);
but it gives me the same as before ($10.00)
Any idea on how to get a result like this: $(10.00)
.
Solution
itemPrice.ToString(@"$#,##0.00;$\(#,##0.00\)");
Should work. I just tested it on PowerShell:
PS C:\Users\Jcl> $teststring = "{0:$#,##0.00;$\(#,##0.00\)}"
PS C:\Users\Jcl> $teststring -f 2
$2,00
PS C:\Users\Jcl> $teststring -f -2
$(2,00)
Is that what you want?
OTHER TIPS
Use Jcl's solution and make it a nice extension:
public static string ToMoney(this object o)
{
return o.toString("$#,##0.00;$\(#,##0.00\)");
}
Then just call it:
string x = itemPrice.ToMoney();
Or another very simple implementation:
public static string ToMoney(this object o)
{
// note: this is obviously only good for USD
return string.Forma("{0:C}", o).Replace("($","$(");
}
You would have to manually split this up, since it is a non-standard formatting.
string.Format("{0}{1:n2}", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol, itemprice);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow