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

前端 未结 14 869
一整个雨季
一整个雨季 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:00

    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

提交回复
热议问题