我在Stackoverflow上看到了很多问题,涉及到在两次加注之后隐藏.0,但是每个答案都说要使用DecimalFormat并执行#.#来隐藏它。除了这不是我想要的。

对于双精度不能仅以.0结尾的每种可能性,我希望它们是它们的状态。除非它以.0结尾,否则将其删除。换句话说,我想一直保持精度,除非它以.0结尾。

例子:

0.0000000000000000042345470000230 -> 0.0000000000000000042345470000230
0.4395083451 -> 0.4395083451
46547453.00024235 -> 46547453.00024235

435.0 -> 435


有没有办法可以做到这一点?

进一步的例子:

这个问题here具有我正在谈论的答案类型:


  使用DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));



上面的###.#表示我将出现前3位数字,一个句点,然后是其后的第一个数字。不管我的价值如何,只有第一个小数都会被格式化。

最佳答案

好吧,实际上这并不复杂。只需检查一下(它甚至可以为您提供最精确的数字):

//Square root of 5 will give you a lot of decimals
BigDecimal d1 = new BigDecimal(sqrt(5));
//5 will give you none
BigDecimal d2 = new BigDecimal(5);
//Print and enjoy
System.out.println(d1.stripTrailingZeros());
System.out.println(d2.stripTrailingZeros());


stripTrailingZeros()将删除任何纯0的痕迹,但是如果存在其他数字,则保留格式。

10-05 21:04
查看更多