I got a little problem with a function I need in my java progam. I want to check the total amount of digits, a 'double' variable has. (e.g.: 5 should return 1, 5.0034 should return 5, and 2.04 should return 3.) My function is this:
private int getDoubleLength (double a) {
int len = 0;
while (a != (int) a) {
a *= 10;
}
while (a > 1) {
len ++;
a/=10;
}
System.out.println(String.format("Double %f has %d digits.",a,len));
return len;
}
Now this works perfectly, but when I am making some mathematical calculations, you get the slight errors of doubles: I divide 10 by cos(60), which is 0,5. The answer should be 20.0, but the program gives a 20.000000000000004 (that number, I copied it). My while loop gets stuck, and the program hangs.
Any ideas? (Or other great solutions for checking the digits of a number!)