是否可以将String.format用于条件小数点? [英] Is it possible to use String.format for a conditional decimal point?

查看:104
本文介绍了是否可以将String.format用于条件小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否可以使用String.format仅在实际需要时才显示小数?例如,如果我这样做:

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

它将格式化: "1.2222"->"1.2" "1.000"->"1.0" 等等,

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

,但是在第二种情况下(1.000),我希望它只返回"1".使用String.format是否可能,或者必须使用DecimalFormatter?

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?

如果必须使用十进制格式化程序,是否需要为每种想要的格式类型制作一个单独的DecimalFormatter? (最多1个小数位,最多2个小数位,等等)

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)

推荐答案

否,您必须使用

根据需要放置尽可能多的#; DecimalFormat将仅打印认为有效的位数,最多可以打印# s个数字.

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.

这篇关于是否可以将String.format用于条件小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆