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

前端 未结 14 848
一整个雨季
一整个雨季 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 11:58

    For integer values represented by a double, you can use this code, which is much faster than the other solutions.

    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);
    }
    

提交回复
热议问题