将double转换为不带小数位的String的最佳方法

Best way to convert a double to String without decimal places

将双精度数转换为不带小数位的字符串的最佳方法是什么?

String.valueOf((int) documentNumber)?

双打小数点后总是0。我不需要舍入或截断

您可以将双精度数转换为具有最低必要精度的字符串:

public static String ceonvert(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

或者这个:

> new DecimalFormat("#.##").format(2.199); //"2.2"

你可以试试这个:

String numWihoutDecimal = String.valueOf(documentNumber).split("\.")[0];

我不确定这是不是最好的方式,但我确定这是最短的方式:

((int)documentNumber) + ""

如果您确定 double 确实是一个整数,请使用这个:

NumberFormat nf = DecimalFormat.getInstance();
nf.setMaximumFractionDigits(0);
String str = nf.format(documentNumber);

作为奖励,通过这种方式您可以将语言环境配置保持为千位分隔符。

编辑
我添加了这个先前删除的选项,因为它似乎对 OP 很有用:

Double.valueOf(documentNumber).intValue();

鉴于新编辑的问题表明双打实际上是整数,我想说你建议的答案 String.valueOf((int) documentNumber) 很好。

引号 + 双引号

字符串 s = "" + 0.07;

大声笑这是最好的方法,(显然对于有经验的程序员)!

将双精度型转换为字符串的最简单方法是先使用引号,然后再使用双精度型。 双 d = 123; 字符串 a = "" + d;

另一种方法是使用 toString 方法,如果你想隐藏你的转换方式

public String toString()
{
   String a + ""  d;
}