目前我正在使用String.format("%.1f", number)
将double格式化为仅有1位小数。然而,它们显示为例如0.2
。是否可能在没有 0
的情况下进行格式化,使其看起来像.2
?
当我搜索此问题时,我只能找到如何添加更多前导0的解决方案...
目前我正在使用String.format("%.1f", number)
将double格式化为仅有1位小数。然而,它们显示为例如0.2
。是否可能在没有 0
的情况下进行格式化,使其看起来像.2
?
当我搜索此问题时,我只能找到如何添加更多前导0的解决方案...
DecimalFormat
:
DecimalFormat formatter = new DecimalFormat("#.0"); // or the equivalent ".0"
System.out.println(formatter.format(0.564f)); // displays ".6"
System.out.println(formatter.format(12.546f)); // displays "12.5"
System.out.println(formatter.format(12f)); // displays "12.0"
#
而不是 0
表示当值不存在时不显示任何数字。#.#
作为格式说明符。如果没有小数部分,则小数点将不会出现:DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(0.564f)); // displays ".6"
System.out.println(formatter.format(12.546f)); // displays "12.5"
System.out.println(formatter.format(12f)); // displays "12"
0.564
被四舍五入了吗?如果这不符合你的口味,你可以通过使用 DecimalFormat.setRoundingMode(RoundingMode mode)
方法来更改所使用的四舍五入算法。如果您只想截断额外的数字,则使用 RoundingMode.DOWN
。
substring
还是replace
更合适? - OneCricketeerif(string.beginsWith("0.")) string = string.substring(1);
- Compass