How do I get NumberFormat.getCurrencyInstance()
to print negative USD currency values with a minus sign?
For negative numbers, you can display the number with a leading red minus sign surrounded by parentheses or in red surrounded by parentheses. Currency formats—The currency formats are similar to the number formats, except that the thousands separator is always used.
The words "losses" and "deficit" make the minus sign redundant and unnecessary. +1, except that you have both "$" and "dollar" in $2.4 million dollar.
It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance()
to do it in a locale-independent manner. Here's what I did (tested on Android):
DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance(); String symbol = formatter.getCurrency().getSymbol(); formatter.setNegativePrefix(symbol+"-"); // or "-"+symbol if that's what you need formatter.setNegativeSuffix("");
IIRC, Currency.getSymbol()
may not return a value for all locales for all systems, but it should work for the major ones (and I think it has a reasonable fallback on its own, so you shouldn't have to do anything)
Here is one I always end up using either in a java class or via the fmt:formatNumber jstl tag:
DecimalFormat format = new DecimalFormat("$#,##0.00;$-#,##0.00"); String formatted = format.format(15.5);
It always produces at least a $0.00 and is consistent when displayed. Also includes thousands seperators where needed. You can move the minus sign in front of the dollar sign if that is your requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With