How do I print a double value without scientific notation using Java?

前端 未结 14 1124
一整个雨季
一整个雨季 2020-11-21 11:52

I want to print a double value in Java without exponential form.

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

It shows this

14条回答
  •  耶瑟儿~
    2020-11-21 12:06

    I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:

    this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.

    It looks like this in its shortest form:

    return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
    

    Pre Java 8, this results in "0.0" for any zero-valued Doubles, so you would need to add:

    if (myDouble.doubleValue() == 0)
        return "0";
    

    NaN and infinite values have to be checked extra.

    The final result of all these considerations:

    public static String doubleToString(Double d) {
        if (d == null)
            return null;
        if (d.isNaN() || d.isInfinite())
            return d.toString();
    
        // Pre Java 8, a value of 0 would yield "0.0" below
        if (d.doubleValue() == 0)
            return "0";
        return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
    }
    

    This can also be copied/pasted to work nicely with Float.

提交回复
热议问题