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

Despicable picture Despicable · Apr 19, 2013 · Viewed 326.3k times · Source

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

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

It shows this E notation: 1.2345678E7.

I want it to print it like this: 12345678

What is the best way to prevent this?

Answer

Eric Leschinski picture Eric Leschinski · Jan 5, 2014

Java prevent E notation in a double:

Five different ways to convert a double to a normal number:

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Runner {
    public static void main(String[] args) {
        double myvalue = 0.00000021d;

        //Option 1 Print bare double.
        System.out.println(myvalue);

        //Option2, use decimalFormat.
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(8);
        System.out.println(df.format(myvalue));

        //Option 3, use printf.
        System.out.printf("%.9f", myvalue);
        System.out.println();

        //Option 4, convert toBigDecimal and ask for toPlainString().
        System.out.print(new BigDecimal(myvalue).toPlainString());
        System.out.println();

        //Option 5, String.format 
        System.out.println(String.format("%.12f", myvalue));
    }
}

This program prints:

2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000

Which are all the same value.

Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?

http://youtube.com/watch?v=PZRI1IfStY0