64位double可以精确地表示整数+/- 253。

鉴于这一事实,我选择使用双类型作为我所有类型的单一类型,因为我的最大整数是一个无符号的32位数字。

但现在我必须打印这些伪整数,但问题是它们也和实际的双精度数混合在一起。

那么如何在Java中很好地打印这些double呢?

我试过String。format("%f", value),这很接近,除了我得到了很多小值的末尾零。

下面是%f的输出示例

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

我想要的是:

232
0.18
1237875192
4.58
0
1.2345

当然,我可以写一个函数来修剪这些零,但由于字符串操作,这是大量的性能损失。我能用其他格式的代码做得更好吗?


Tom E.和Jeremy S.的答案是不可接受的,因为他们都任意舍入到小数点后两位。请先理解问题再回答。


请注意字符串。Format (Format, args…)依赖于语言环境(见下面的答案)。


当前回答

new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2

0表示最小位数 渲染#数字

其他回答

这里有一个实际有效的答案(这里不同答案的组合)

public static String removeTrailingZeros(double f)
{
    if(f == (int)f) {
        return String.format("%d", (int)f);
    }
    return String.format("%f", f).replaceAll("0*$", "");
}
new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2

0表示最小位数 渲染#数字

String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
    g = g.substring(0, g.length() - 1);
    if (g.endsWith("."))
    {
        g = g.substring(0, g.length() - 1);
    }
}

最好的方法如下:

public class Test {

    public static void main(String args[]){
        System.out.println(String.format("%s something", new Double(3.456)));
        System.out.println(String.format("%s something", new Double(3.456234523452)));
        System.out.println(String.format("%s something", new Double(3.45)));
        System.out.println(String.format("%s something", new Double(3)));
    }
}

输出:

3.456 something
3.456234523452 something
3.45 something
3.0 something

唯一的问题是最后一个。0没有被删除。但如果你能接受这一点,那么这种方法就最好了。%。2f会四舍五入到小数点后两位。DecimalFormat也是如此。如果你需要所有的小数点后数位,但不需要后面的零,那么这个方法是最好的。

String.format("%.2f", value);