How to pass a number in scientific notation in Java?

9

I'm using a method to not display scientific notation

DecimalFormat dfor = new DecimalFormat("#");
dfor.setMaximumFractionDigits(10);  
txtTexto.setText(df.format(valorDouble));

But when you press a button it switches to scientific notation.

    
asked by anonymous 10.03.2015 / 13:55

1 answer

6

Maybe BigDecimal#toPlainString() can serve this purpose.

  

toPlainString : Returns the string representation of this BigDecimal without an exponent field. For values with a positive scale, the number of digits to the right of the decimal point is used to indicate scale.

See an example:

    Double valorDouble = 7.89894691515E12;
    String valorStr =  new BigDecimal(valorDouble).toPlainString();
    System.out.println(valorStr); // 7898946915150

DEMO

Update : I misunderstood the question, the above code does the opposite of what was asked, it converts a scientific-sized number to string .

To pass a number to scientific notation, for example 10000000000 , can be done like this:

DecimalFormat df = new DecimalFormat("0E0");    // Formato

Double valorDouble =  10000000000.0;
System.out.println(df.format(valorDouble));     // 1E10

DEMO

To pass a number to five decimal places for scientific notation, do as follows:

    DecimalFormat df = new DecimalFormat("0.0000E0");

    Double valorDouble =  12345.0;
    System.out.println(df.format(valorDouble)); // 1.2345E4

DEMO

If the format used is null, a NullPointerException exception is thrown, if it is invalid, IllegalArgumentException is thrown.

link below explains how to create and customize formats, although it is in English, it is quite understandable and contains examples.

10.03.2015 / 14:12