Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number with leading sign

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)

like image 490
usr-local-ΕΨΗΕΛΩΝ Avatar asked Mar 09 '11 08:03

usr-local-ΕΨΗΕΛΩΝ


3 Answers

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
like image 106
JB Nizet Avatar answered Nov 14 '22 04:11

JB Nizet


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
like image 21
Tomasz Nurkiewicz Avatar answered Nov 14 '22 03:11

Tomasz Nurkiewicz


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)

like image 8
t3az0r Avatar answered Nov 14 '22 04:11

t3az0r