Format a number with leading sign

usr-local-ΕΨΗΕΛΩΝ picture usr-local-ΕΨΗΕΛΩΝ · Mar 9, 2011 · Viewed 54.6k times · Source

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)

Answer

JB Nizet picture JB Nizet · Mar 9, 2011

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