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

孤者浪人 提交于 2020-01-02 01:18:08

问题


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);

it will format: "1.2222" -> "1.2" "1.000" -> "1.0" etc,

but in the second case (1.000) I want it to return just "1". Is this possible with String.format, or am going to have to use a DecimalFormatter?

If I have to use a decimal formatter, will I need to make a separate DecimalFormatter for each type of format I want? (up to 1 decimal place, up to 2 decimal places, etc)


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/2164649/is-it-possible-to-use-string-format-for-a-conditional-decimal-point

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!