December 2002 Technical Tip – Java's Dirty Secret

Most non-integer arithmetic in Java is done using doubles. Floats are usually avoided as everyone knows they tend to be imprecise. But doubles are prone to error as well. This is the dark side of Java that is rarely mentioned in text books. Here's a real simple example. The following program calculates miles driven as the ending odometer reading minus the beginning odometer reading:

public class Mileage
   public static void main(String[] args)
      double begOdo = 52390.7;
      double endOdo = 52557.1;
      double miles = endOdo - begOdo;
      System.out.println("You drove " + miles + " miles." );

The output appears as follows. The answer should be 166.4.

You drove 166.40000000000146 miles.

Here's another example. The following program uses before tax amount and sales tax rate to calculate the after tax amount:

public class SalesTax
   public static void main(java.lang.String[] args)
      double beforeTax = 123.45;
      double salesTaxRate = .065;
      double afterTax = beforeTax * (1 + salesTaxRate);
      System.out.println( "After tax amount is " + afterTax);

The output appears as follows. The answer should be 131.47425.)

After tax amount is 131.47424999999998

To make matters worse, only some numbers have this problem. You might test all day and not come across errors such as these. I keep a running list of numbers which cause problems such as these, and I make sure I use those numbers as test cases in future programs.

There is a solution, but that will be the topic of next month's technical tip.

Caliber Data Training is pleased to offer training in Java programming. We have recently rewritten our Visualage Java course to use the Websphere Application Development suite. We hope you will consider us when deciding upon a training provider…and we won't sugar coat it!

Go to the articles index. Written by Bill Qualls. Copyright © 2002 by Caliber Data Training 800.938.1222