Reputation: 3
I´m trying out eclipse for the first time and I´m trying to programm an Calculator with a numpad. Currently i´m programming the comma function but my code doesnt work.
Here is my code for the decimal places:
System.out.println(first+"");
System.out.println(dec_length(first));
first=((first*Math.pow(10, dec_length(first)))+1) / Math.pow(10, dec_length(first));
textfield.setText(""+format.format(first));
The method dec_length() is:
public static int dec_length(double input) {
String param=(""+input);
String vergleich =(".0");
String sub= param.substring((param.indexOf('.')));
if (sub.equals(vergleich)) {
return 1;
} else
return sub.length();
}
When I try it it works for the first 2 decimal places but then it stops working.
Here is the console output:
5.0
1
5.1
2
5.109999999999999
16
5.109999999999999
16
5.109999999999999
16
Does anybody know whats wrong with this?
Upvotes: 0
Views: 448
Reputation: 777
The problem is that you assume that all decimal places can be represented exactly by the double type. But that is not the case.
I suggest you store the number as a string until you use it for calculation:
String first = "0";
And then either add a digit or a comma(you should of course make sure there is only one .
in your number):
first += digit; // Add a digit from 0 to 9
first += '.'; // Call this when the comma function is called.
And afterwards, when you want to do the calculation part you can easily parse the string to a double:
double value = Double.parseDouble(first);
Upvotes: 2