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

后端 未结 2 1222
不思量自难忘°
不思量自难忘° 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:31

    This might get you what your looking for; I'm not sure of the requirements or context of your request.

    float f;
    f = 1f
    System.out.printf(f==Math.round(f) ? "%d\n" : "%s\n", f); //1
    f = 1.555f
    System.out.printf(f==Math.round(f) ? "%d\n" : "%s\n", f); //1.555
    

    Worked great for what I needed.

    FYI, above, System.out.printf(fmt, x) is like System.out.print(String.format(fmt, x)

提交回复
热议问题