0

Im running in to this weird problem when I divide doubles in java.

System.out.println((0.39281 + 0.39281 + 0.39281)/ 3.0);

which gives me 0.39281000000000005

I was expecting obviously 0.39281 as the answer but in reality its giving me this trailing remainder too. I am just really confused as to why this is so because when i run System.out.println((0.39281 + 0.39281)/ 2.0), i get what i expected.

What would be a good work around for this, assuming i want to store accurate values, not necessarily printing them

Thanks guys

  • 3
    Floating point arithmetic is inexact. It is a fundamental fact. Independent of the programming language you are using. – Stephen C Jul 17 '21 at 04:36
  • 1
    If you want more accuracy, use `BigDecimal`. But be aware that even `BigDecimal` cannot store all numbers with 100% accuracy. It is a property of the underlying mathematics. (For example, you cannot express 1/3 as a decimal number without using an *infinite* number of 3's.) – Stephen C Jul 17 '21 at 06:07

0 Answers0