Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format negative amount of USD with a minus sign, not brackets (Java)

How do I get NumberFormat.getCurrencyInstance() to print negative USD currency values with a minus sign?

like image 936
Žygimantas Avatar asked Jan 13 '10 12:01

Žygimantas


People also ask

How do you format a negative dollar amount?

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.

How do you write negative currency in words?

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.


2 Answers

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)

like image 140
ageektrapped Avatar answered Oct 17 '22 15:10

ageektrapped


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.

like image 45
Gennadiy Avatar answered Oct 17 '22 14:10

Gennadiy