0

Both were hoping for a 0.41 result, but the result was not what I expected. I know this result is a floating point difference. Is there a way to always get the expected result without worrying about doing this kind of floating point arithmetic in Java?

    public class Main {
        public static void main(String[] args) {
            System.out.println(41 / 100.0);
            System.out.println(41 * 0.01);
        }
    }

Printed output:

0.41
0.41000000000000003
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
newbieeyo
  • 663
  • 4
  • 12
  • 2
    You can always use BigDecimal – Morph21 Apr 15 '22 at 10:58
  • 1
    In short - as soon as you perform calculations on floating point types, you need to know how they are defined. They are not very intuitive and come with lots of pitfalls, and this is not really specific to the Java language. – Hulk Apr 15 '22 at 11:02
  • @Szprota21 gives the right suggestion. `BigDecimal.valueOf(41).multiply(new BigDecimal("0.01"))` prints as `0.41`. – Ole V.V. Apr 15 '22 at 12:18

0 Answers0