Format a number with leading sign

后端 未结 4 1729
耶瑟儿~
耶瑟儿~ 2020-12-05 06:39

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 06:55

    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
    

提交回复
热议问题