Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Computers can represent only a finite number of digits. It Consequently, it is consequently impossible to precisely represent repeating binary sequences of floating point numbers. This includes many finite decimal numbers, such as 1/10 which have repeating binary representations.

When precise computation is necessary, and especially when doing currency calculations, consider alternative representations that may be able to completely represent values rather than employing the floating point representations float and double.

...

Code Block
bgColor#FFcccc
double dollar = 1.0;
double dime = 0.1;
int number = 7;
System.out.println ("A dollar less " + number + " dimes is $" +
		    (dollar - number * dime) );

Unfortunately, because of the imprecision of floating point arithmetic, this program prints:

...

Code Block
bgColor#ccccff
long dollar = 100;
long dime = 10;
int number = 7;
System.out.println ("A dollar less " + number + " dimes is " +
		    (dollar - number * dime) + " cents" );

This code prints outoutputs: A dollar less 7 dimes is 30 cents

...

An alternative approach is to use the BigDecimal type, though it is less efficient.

Code Block
bgColor#ccccff
import java.math.BigDecimal;

BigDecimal dollar = new BigDecimal("1.0");
BigDecimal dime = new BigDecimal("0.1");
int number = 7;
System.out.println ("A dollar less " + number + " dimes is $" +
	(dollar.subtract( new BigDecimal(number).multiply(dime) )) );

This code prints outoutputs: A dollar less 7 dimes is $0.3

...