How to pass a number in scientific notation in Java?

Asked

Viewed 2,783 times

9

I’m using a method not to 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.

  • Did that work out like you wanted? I ask this because I was in doubt if what I actually answered answers what you asked.

  • @Qmechanic73 nothing true I want to display in scientific notation, because to display in no scientific notation I already have command that this in question.

  • 1

    Ah yes, sorry then, it’s something thus what you want to do?

  • @Qmechanic73 and something like that

  • As you wanted to do exactly?

  • @Qmechanic73 I will ask a question, if you think better I open another question, as I do to read 10 houses example 10000000000 ai apply the scientific notation you passed on the link.

  • I’m not a expert in Java but, I think that should do it. The L in the end it is necessary when it is a very high value.

  • thanks but I’ll open this question because I want to small number too.

  • I’ve tweaked the answer a little bit, if there’s anything else I can put on it, let me know. :)

Show 4 more comments

1 answer

6


Maybe the function BigDecimal#toPlainString() may serve that purpose.

toPlainString: Returns the representation of string 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.

Take an example:

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

DEMO

Updating: I misunderstood the question, the code above does the opposite of what was asked, it converts a number with scientific format 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 of five decimal places for scientific notation, do so:

    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, an exception NullPointerException will be launched if invalid, IllegalArgumentException is launched.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.