Format a number with leading sign

JavaFormattingNumbersCurrency

Java Problem Overview


How do I format in Java a number with its leading sign?

Negative numbers are correctly displayed with leading -, but obviously positive numbers are not displayed with +.

How to do that in Java? My current currency format string is \#\#\#,\#\#\#,\#\#\#,\#\#\#,\#\#0.00 (yes, I need to format positive/negative currency values)

Java Solutions


Solution 1 - Java

Use a negative subpattern, as described in the javadoc for DecimalFormat.

DecimalFormat fmt = new DecimalFormat("+#,##0.00;-#");
System.out.println(fmt.format(98787654.897));
System.out.println(fmt.format(-98787654.897));

produces (in my French locale where space is the grouping separator and the comma is the decimal separator) :

+98 787 654,90
-98 787 654,90

Solution 2 - Java

API for Formatter provides an example:

Formatter formatter = new Formatter();
System.out.println(formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E));
//e =    +2,7183

Solution 3 - Java

I did:

private NumberFormat plusMinusNF = new DecimalFormat("+#;-#");

Integer newBalance = (Integer) binds.get("newBalance");
bindsForUpdate.put("plusMinus", plusMinusNF.format(newBalance));

which formatted positive integers, e.g. 5 to "+5" and negative integers, e.g -7 to "-7" (as expected)

Solution 4 - Java

> 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

Source: https://stackoverflow.com/questions/2056400/format-negative-amount-of-usd-with-a-minus-sign-not-brackets-java

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionusr-local-ΕΨΗΕΛΩΝView Question on Stackoverflow
Solution 1 - JavaJB NizetView Answer on Stackoverflow
Solution 2 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 3 - Javat3az0rView Answer on Stackoverflow
Solution 4 - JavaMohamed SalighView Answer on Stackoverflow