Is it possible to use String.format for a conditional decimal point?

后端 未结 2 1219
不思量自难忘°
不思量自难忘° 2021-01-11 12:19

In java, is it possible to use String.format to only show a decimal if there is actually a need? For example, if I do this:

String.format(\"%.1f\", amount);         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-11 12:36

    No, you have to use DecimalFormat:

    final DecimalFormat f = new DecimalFormat("0.##");
    System.out.println(f.format(1.3));
    System.out.println(f.format(1.0));
    

    Put as many #s as you'd like; the DecimalFormat will only print as many digits as it thinks are significant, up to the number of #s.

提交回复
热议问题