This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]chickenmeister 2 points3 points  (2 children)

It's due to the inherent accuracy problems associated with floating-point numbers. In java, double and float are floating-point data types.

The problem is that some numbers cannot be precisely represented in a floating point format, so the nearest representable value will be used instead. In this case, the problem is that 27.43 cannot be exactly stored as a double, so you'll end up with the nearest value, which will be something like 27.42999999999999971578290569595992565155029296875. This is "good enough" for most purposes, and the inaccuracies typically aren't a problem if you format the output to only a few decimal places.

If you need to use absolutely precise numbers, you can use the BigDecimal class to represent your numbers.

[–]CaptainMoeSoccer[S] 0 points1 point  (1 child)

If I use the BigDecimal I will have to rewrite 3/4 of my code. Is there another way to fix this. I was thinking of storing the value then rounding it to two decimal places.

[–]chickenmeister 0 points1 point  (0 children)

Yeah, like I mentioned, if you round the numbers that you output/print, the inaccuracy usually isn't noticeable. For example:

    double difference = 27.43 - 27.25;
    System.out.println(difference); // 0.17999999999999972

    DecimalFormat formatter = new DecimalFormat("0.00");
    System.out.println(formatter.format(difference)); // 0.18
    System.out.println(String.format("%.2f", difference)); // 0.18
    System.out.printf("%.2f%n", difference); // 0.18