Tuffy G
Tuffy G

Reputation: 1521

android incorrect subtraction from user provided input

lets start with a abit of math.

target weight = 8.4 current weight = 9.1 current weight - target weight = 0.7 (you would think so)

if( obj != null && obj.targetWeight != null && obj.currentWeight != null) {
            try {
                double i = Double.parseDouble( obj.targetWeight );
                double o = Double.parseDouble( obj.currentWeight);
                //do something if target weight is a number
                if(i>o){
                    outputEditText.setText ("Congratulations. you have passed your target weight");
                }
                else if (i<o){
                    outputEditText.setText(
                            "Your Target Weight is " + obj.targetWeight +obj.unit + "\n" + 
                                    "Your Current Weight is " + obj.currentWeight + "\n" +
                                    "Difference is " + (o - i));
                }

according to the above 8.4-9.1 = 0.6999999999999993

both target and current weights are user provided inputs that are parsed as double.

does anyone know what i'm doing wrong

many thanks

Upvotes: 0

Views: 204

Answers (3)

Tuffy G
Tuffy G

Reputation: 1521

Thanks everyone for your answers.

it turns out the world of the machines is different to what my brain might think like.

here is what i've done to solve my issue.

DecimalFormat df = new DecimalFormat("####.##"); 

                    String b = df.format(o-i);

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

You're not doing anything wrong. Welcome to the wonderful world of floating-point arithmetic! Lots of numbers that look nice and even to us can't actually be represented exactly in the binary number system used by your computer.

The answer to your immediate problem is formatting. You can never simply print raw double-precision numbers; you always have to use, e.g., DecimalFormat to present an appropriate number of decimal places. Your number, rounded to (for example) five decimal places, would print as 0.7 .

Upvotes: 4

lrAndroid
lrAndroid

Reputation: 2854

Not all decimals (i.e. doubles) can be expressed perfectly in base 2. Thus, you often get a round off, resulting in what you've just seen. The output of .6999999... is is the computer's best approximation of the subtraction using the approximate base 2 representation of your input.

Upvotes: 1

Related Questions