Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...