Monetary values are usually program in financial application. When you deal with “money” value, it’s always come to a question, should i use double or float variable to represent the monetary values?

1. Monetary values in Java – double

Here is an example to use double to represent the monetary values in Java.

import java.math.BigDecimal;
 
public class PrintChangeAmount {
  public static void main(String[] argv) {
 
	  System.out.println("--- Normal Print-----");
	  System.out.println(2.00 - 1.1);
	  System.out.println(2.00 - 1.2);
	  System.out.println(2.00 - 1.3);
	  System.out.println(2.00 - 1.4);
	  System.out.println(2.00 - 1.5);
	  System.out.println(2.00 - 1.6);
	  System.out.println(2.00 - 1.7);
	  System.out.println(2.00 - 1.8);
	  System.out.println(2.00 - 1.9);
	  System.out.println(2.00 - 2);
  }
}

Output

--- Normal Print-----
0.8999999999999999
0.8
0.7
0.6000000000000001
0.5
0.3999999999999999
0.30000000000000004
0.19999999999999996
0.10000000000000009
0.0

In the output, it cannot calculate all double decimals precisely.

2. Monetary values in Java – BigDecimal

To avoid the decimal issue above, you can use BigDecimal to represent the monetary values.

import java.math.BigDecimal;
 
public class PrintChangeAmount {
  public static void main(String[] argv) {
 
	  System.out.println("--- BigDecimal-----");
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.1")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.2")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.3")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.4")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.5")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.6")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.7")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.8")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.9")));
	  System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("2")));
  }
}

Output

--- BigDecimal-----
0.90
0.80
0.70
0.60
0.50
0.40
0.30
0.20
0.10
0.00

BigDecimal performs exact decimal arithmetic.

Conclusion

In Java, it’s recommended to use BigDecimal to represent the monetary calculations. However BigDecimal calculations are slower than those with primitive data type calculations, which may be an issue for heavy decimal calculations program, but there’s should be no problem for most programs.

Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to the charity, thanks.

Related Posts

Popular Posts