Why do you want to do this? A concept like "the number of decimal
places" seems to relate more naturally to the String form in which a
number is presented, rather than to a double, say. Often people decide
in advance how many decimal places they want (or how many make
sense) in the string forms of numbers, and round the numbers
accordingly.
You could try something like this:import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DP {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
double d = Double.parseDouble(in.readLine());
System.out.printf("dp=%d %f%n", getDP(d), d);
}
/**
* Returns how many times a number must be multiplied by 10 before
* the decimal bit compares equal to zero.
*/
private static int getDP(double d) {
double num = d - Math.floor(d);
//System.out.println("num="+num);
int ret = 0;
while(num != 0) {
ret++;
num *= 10;
num = num - Math.floor(num);
//System.out.println("num="+num);
}
return ret;
}
}
It "works" for the two examples you give. But it gives results that
can be unexpected (unless you expect them). For instance 0.99999
must be multiplied by 10 49 times before the decimal part becomes
zero.
The "number of decimal places" is not obvious for computer numbers
that are necessarily imprecise. In mathematics centuries of thought
finally managed to establish that pi and e don't have a number of
decimal places (they go on for ever). Mathematicians still have no
clue about the number pi+e.