views:

307

answers:

3

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

+1  A: 

It's probably best to create your own DecimalFormat if you want a specific format rather than relying on the default.

Edit: You could probably also cast the result of NumberFormat.getCurrencyInstance() to DecimalFormat and adjust it to your preferences.

Michael Borgwardt
Probably you are right, but my application should be able to format currency in may locales. Wouldn't it be too hard to implement formating for all those locales?
Žygimantas
+1  A: 

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.

Gennadiy
A: 

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)

ageektrapped