BigDecimal 去除尾随零
BigDecimal stripping trailing zeros
我有一个 BigDecimal 值,想要删除某个点之前的尾随零。以下是一些示例:
1.00000 -> 1.0
12.2 -> 12.2
19.9300 -> 19.93
请注意第一种情况,当所有小数都为零时,我们想要保留 1 个小数位。我想避免 stripTrailingZeros()
因为在某些情况下它可以转换为科学记数法,(例如 1E+1)
编辑:在这种情况下,BigDecimal 的比例已经设置为大于 5 的值。
您确实需要使用 stripTrailingZeros()
to eliminate zeroes, but you can then use setScale()
以确保您至少得到小数点后一位数字。
for (String s : new String[] { "1.00000", "12.2", "19.9300", "1e+10", "1e-10", "0" }) {
BigDecimal value = new BigDecimal(s);
value = value.stripTrailingZeros();
if (value.scale() < 1)
value = value.setScale(1);
System.out.println(value);
}
输出
1.0
12.2
19.93
10000000000.0
1E-10
0.0
如果你不想要1E-10
,那么你必须调用toPlainString()
, because that's how the normal toString()
才会输出这么小的值。
我有一个 BigDecimal 值,想要删除某个点之前的尾随零。以下是一些示例:
1.00000 -> 1.0
12.2 -> 12.2
19.9300 -> 19.93
请注意第一种情况,当所有小数都为零时,我们想要保留 1 个小数位。我想避免 stripTrailingZeros()
因为在某些情况下它可以转换为科学记数法,(例如 1E+1)
编辑:在这种情况下,BigDecimal 的比例已经设置为大于 5 的值。
您确实需要使用 stripTrailingZeros()
to eliminate zeroes, but you can then use setScale()
以确保您至少得到小数点后一位数字。
for (String s : new String[] { "1.00000", "12.2", "19.9300", "1e+10", "1e-10", "0" }) {
BigDecimal value = new BigDecimal(s);
value = value.stripTrailingZeros();
if (value.scale() < 1)
value = value.setScale(1);
System.out.println(value);
}
输出
1.0
12.2
19.93
10000000000.0
1E-10
0.0
如果你不想要1E-10
,那么你必须调用toPlainString()
, because that's how the normal toString()
才会输出这么小的值。