我想在Java中打印一个没有指数形式的双值。

double dexp = 12345678;
System.out.println("dexp: "+dexp);

它显示了这个E符号:1.2345678E7。

我希望它像这样打印:12345678

预防这种情况的最好方法是什么?


当前回答

你可以尝试使用DecimalFormat。使用这个类,您可以非常灵活地解析数字。 您可以精确地设置您想要使用的模式。 以你为例:

double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678

其他回答

使用字符串。格式(“%。0 f”,数量)

%。0f表示0小数

String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);

这可能是一个切线....但如果你需要把一个数值作为一个整数(太大而不能成为一个整数)放入一个序列化器(JSON等),那么你可能需要“biginteger”

例子:

值为字符串- 7515904334

我们需要在Json消息中以数字形式表示它:

{
    "contact_phone":"800220-3333",
    "servicer_id":7515904334,
    "servicer_name":"SOME CORPORATION"
}

我们不能打印它,否则会得到这个:

{
    "contact_phone":"800220-3333",
    "servicer_id":"7515904334",
    "servicer_name":"SOME CORPORATION"
}

像这样向节点添加值会产生期望的结果:

BigInteger.valueOf(Long.parseLong(value, 10))

我不确定这是否真的切题,但由于这个问题是我在寻找解决方案时最热门的问题,我想我应该在这里分享一下,以造福于那些搜索不好的人。: D

对于用double表示的整数值,可以使用这段代码,它比其他解决方案快得多。

public static String doubleToString(final double d) {
    // check for integer, also see https://stackoverflow.com/a/9898613/868941 and
    // https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
    if (isMathematicalInteger(d)) {
        return Long.toString((long)d);
    } else {
        // or use any of the solutions provided by others, this is the best
        DecimalFormat df = 
            new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
        return df.format(d);
    }
}

// Java 8+
public static boolean isMathematicalInteger(final double d) {
    return StrictMath.rint(d) == d && Double.isFinite(d);
}

这对我很有用。输出将是一个字符串。

String.format("%.12f", myvalue);

转换科学符号的好方法

String.valueOf (YourDoubleValue.longValue ())