4

可能重复:
如何很好地将浮动类型格式化为字符串?

我有号码:

Double d1=(Double)0;
Double d2=(Double)2.2;
Double d3=(Double)4;

当我使用 to String 时,我得到 0.0、2.2、4.0,但我想看到 0、2.2、4。我该怎么做?

4

2 回答 2

18

使用DecimalFormat.formatinsted Double.toString

Double d1 = (Double)0.0;
Double d2 = (Double)2.2;
Double d3 = (Double)4.0;

// Example: Use four decimal places, but only if required
NumberFormat nf = new DecimalFormat("#.####");

String s1 = nf.format(d1); // 0
String s2 = nf.format(d2); // 2.2
String s3 = nf.format(d3); // 4

你甚至不需要Doubles ,doubles 就可以了。

于 2013-01-11T06:09:23.860 回答
1

首先使用 String.valueof(YOUR_VARIABLE) 将您的 Double 转换为 String

然后使用下面的功能来做到这一点。

private String getyourNumber(String NUMBER) {
    if(!NUMBER.contains(".")) {
        return NUMBER;
    }

    return NUMBER.replaceAll(".?0*$", "");
}

然后转换你的

字符串加倍Double.parseDouble(YOUR_RETURNED_STRING)

于 2013-01-11T06:09:17.790 回答