Search code examples
javascientific-notation

Convert a number from scientific notation to decimal in JAVA


I have a problem: a number is showing in scientific notation if it has 8 or more digits before the decimal point.
Is there a simple way to convert this number to decimal via a library or something?
I began creating a manual method to parse it out, but it seems overcomplicated.

Any help will be appreciated.

input example: 1.0225556677556E7

Edit: I also need to be able to identify a number that is in scientific notation


Solution

  • You can use NumberFormat your accomplish your goal easily.

    String scientificNotation = "1.0225556677556E7";
    Double scientificDouble = Double.parseDouble(scientificNotation);
    NumberFormat nf = new DecimalFormat("################################################.###########################################");
    decimalString = nf.format(scientificDouble);
    

    To answer you're other question about matching scientific notation strings- you can use a regex and String.matches(). This one isn't perfect although the probability of getting false positives should be very low:

    if(myString.matches("-?[\\d.]+(?:E-?\\d+)?")){
        //do work
    }