The int and long type do represent integral numbers exactly, but the value of float and double type do not represent decimal numbers exactly.
The float and double perform binary floating-point arithmetic. It only provide approximate of the results of arithmetic operations because they are binary and cannot exactly represent negative powers of then (i.e., 10 -1); If you want an exact representation you can use the java.math.BigDecimal class. For example,
import java.math.BigDecimal;
public class Change {
public static void main(String args[]) {
BigDecimal bigD1 = new BigDecimal("2.00");
BigDecimal bigD2 = new BigDecimal("1.10");
System.out.println(bigD1.subtract(bigD2));
}
}
Note that BigDecimals are String-based.
No comments:
Post a Comment