简体   繁体   中英

Scientific notation with E

I am trying to represent the number .0002 as 2.0 x 10 ^ -4 . Here is what I have so far

public static String toScientificNotation(double n) {
    int exponent = 0;
    if( n < 1){
        String doubleValue = Double.toString(Math.abs(n));
        int format = doubleValue.indexOf(".");
        int decimalPlacesToMove = (doubleValue.length() - (format - 1));
    }

No matter what I try i get E in the output. If someone can give me a pseudo code. It would be a great help. I cannot use BigDecimal or anything other than double .

I reworked your method into the following; you can use it as a basis/skeleton to convert the double into the scientific notation you want, avoiding the E altogether. You can expand on it by creating implementations for n > 1 and n < 0

private static String toScienticNotation(double n) {

    String result = "";

    if (n < 1 && n > 0) {

        int counter = 0;
        double answer = n;

        while (answer < 1) {
            answer = answer * 10;
            counter--;
        }

        result = String.valueOf(answer) + " x 10 ^ "
                + String.valueOf(counter);
    }
    return result;
}

It works by multiplying the input n by 10, counter number of times, until n is greater than 1. This is a substitute formula to manually discover the number of decimal points rather than using the String methods.

The method you were using would work fine, but there's an easier way using formatter:

    import java.util.*;
    import java.text.*;
    import java.math.*;

    class Main{
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            NumberFormat formatter = new DecimalFormat();

            double d = input.nextDouble();
            formatter = new DecimalFormat("#.######E0");
            String x = formatter.format(d);
            System.out.println(x.replace("E","*10^");

        }
    }

This will print the scientific notation in the decimal format of #.######E0

For example:

If 200 was inputted, the system would return 2 * 10^2.

Here is a method which (hopefully) converts all kinds of doubles to their [-]Factor * 10 ^ [-]Exponent notation. It's explained inside the code.

edit: There is a very elegant solution by UnknownOctopus . Still I will leave this here as it does not use any formatters or such, just doubles and Strings - I understood the question wrongly and assumed that only such primitives were allowed.

public class Main{
    /**
     * Converts a double to a base10 notation String.
     * 
     * Each String is formatted like this:
     *
     * [-]Factor * 10 ^ [-]Exponent
     *
     * where both, Factor and Exponent, are integer values.
     *
     * @param number the number to convert
     * @return a base10 notation String.
     */
    public static String toScientificNotation(double number) {
        String s = String.valueOf(number);

        int indexPZero = s.indexOf(".0"); // mostly to check if .0 is the end
        int exponent = 0; // simplest case: *10^0

        // Check if the String ends with exactly .0
        if (indexPZero == s.length() - 2) {
            // If the string also has 0s in front of the period, shift those to the 
            // right
            while(s.contains("0.")) {
                number /= 10;
                exponent += 1;
                s = String.valueOf(number);
            }
            // if the string ends in .0 and has no zeros in front of the period we 
            // can format it:
            return String.valueOf(number) + " * 10 ^ " + exponent;
        }

        // If the String does not end in .0, we need to shift to the left.
        // Additionall
        while (indexPZero != s.length() -2) {
            // in case we suddenly reach the scientific notation just substitute it
            s = s.toLowerCase();
            if (s.contains("e")) {
                return s.substring(0, 
                    s.indexOf("e")) + " * 10 ^ " + s.substring(s.indexOf("e")+1);
            }
            // otherwise shift left and reduce the exponent
            number *= 10;
            exponent -= 1;
            s = String.valueOf(number);
            indexPZero = s.indexOf(".0");
        }
        // If we end up here, just write out the number and the exponent.
        return String.valueOf(number) + " * 10 ^ " + exponent;
    }

    public static void main(String... args) {
        double[] vals = { 1, 0.2, 23.4, -32.00004, 0.0002, 10.0 };
        for(double val : vals) {
            System.out.println(val + " becomes " + toScientificNotation(val));
        }
    }
}

Output:

1.0 becomes 1.0 * 10 ^ 0
0.2 becomes 2.0 * 10 ^ -1
23.4 becomes 234.0 * 10 ^ -1
-32.00004 becomes -3200004.0 * 10 ^ -5
2.0E-4 becomes 2.0 * 10 ^ -4
10.0 becomes 1.0 * 10 ^ 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM