Search code examples
javadouble

How to get the exponent of a double in a power of 10 in java?


(Sorry I don't know what is the best keyword to describe this problem.)

The main problem is, if I have a double number in java, say 25.003, how can I know that this number can be written in 25003 x 10^(-3), so that I can get the exponent part (-3)?

The only thing I desire is to get that exponent number (-3). (so I know I can multiply 25.003 by 1000 to make it an integer) Is there any method gives me that exponent number?

Thanks a lot.


Solution

  • This is actually pretty simple if you think of it as a String.

    private static int getExponentForNumber(double number)
    {
        String numberAsString = String.valueOf(number);
        return numberAsString.substring(numberAsString.indexOf('.') + 1).length() * -1;
    }
    

    This is just returning the length after the "." which is your negative exponent. So you can really just use it like that:

    int exponent = getExponentForNumber(25.003);
    int basis = Integer.valueOf(String.valueOf(25.003).replace(".", ""));
    String expression = "25.003 equals " + basis + "*10^" + exponent;
    System.out.println(expression);
    
    25.003 equals 25003*10^-3