Programming Tips - Java: How to represent money

Date: 2021dec17 Keywords: BigInteger Language: Java Q. Java: How to represent money A. Use BigDecimal Don't use float or double since they can't exactly represent decimal numbers. And, of course, for money exactness matters. Here is an example:
import java.math.BigDecimal; class example { public static void main(String[] args) { { double a = 0.03; double b = 0.04; double c = b - a; System.out.println(" double subtraction=" + c); } { BigDecimal a = new BigDecimal("0.03"); BigDecimal b = new BigDecimal("0.04"); BigDecimal c = b.subtract(a); System.out.println("BigDecimal subtraction=" + c); } } }
Outputs:
double subtraction=0.010000000000000002 BigDecimal subtraction=0.01