-1

I am trying to substract 1.0f from 8.6f value and it returns me 7.6000004

float temp=8.6f-1.0f;
Log.e("temp",temp+"");

and it is printing 7.6000004 What was wrong here ? I am or Android ?

Tejas
  • 23
  • 8
  • Hi Tejas, please the title of your question as SO asks you to: "Be specific and imagine you’re asking a question to another person" – Michel Jung Jan 27 '21 at 13:14
  • This is a common thing in java, as you can see here: https://stackoverflow.com/questions/13263650/float-number-is-not-the-expected-number-after-subtraction – Pascal Jan 27 '21 at 13:17

1 Answers1

1

Floating point operations such like this aren't precise; this is a well-known problem in computer science. See also: https://floating-point-gui.de/basic/

It's basically the same problem as if someone asks you to give a precise answer to "What's 1 divided by 3, to 10 decimal places?" - the best answer you could give is 0.3333333334.

But 3 * 0.3333333334 = 1.0000000002

It's a limitation that exists in every number system, just in different cases.

If you need exact numbers, you should use BigDecimal:

import java.math.BigDecimal;

class FloatingPointExample {
    public static void main(String[] args) {
        // Prints 7.6000004
        System.out.println(8.6f - 1.0f);

        // Prints 7.6
        System.out.println(new BigDecimal("8.6").subtract(new BigDecimal("1.0")));

        // Do NOT pass floats to BigDecimal
        // Prints 7.6000003814697265625
        System.out.println(new BigDecimal(8.6f).subtract(new BigDecimal(1.0f)));

        // Do NOT pass doubles to BigDecimal
        // Prints 7.5999999999999996447286321199499070644378662109375
        System.out.println(new BigDecimal(8.6).subtract(new BigDecimal(1.0)));
    }
}
Michel Jung
  • 2,966
  • 6
  • 31
  • 51