简体   繁体   中英

Why does my java Code output a wrong number?

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?

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);

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?

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