Using Float and Double for Monetary or Financial Calculation in Java | Code Factory

Reference Link : Link

Donate : Link

Using double and float for exact calculation

float and double are designed for engineering and scientific calculation and many times doesn’t produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.

package com.codeFactory;import java.math.BigDecimal;/**
* @author code.factory
*
*/
public class Example {
public static void main(String...strings) {
float f1 = 1.25f;
float f2 = 1.05f;
System.out.println("Float f1 - f2 : " + (f1 - f2));

double d1 = 1.25;
double d2 = 1.05;
System.out.println("Double d1 - d2 : " + (d1 - d2));

BigDecimal b1 = new BigDecimal("1.25");
BigDecimal b2 = new BigDecimal("1.05");
System.out.println("BigDecimal(\"\") b1 - b2 : " + (b1.subtract(b2)));

BigDecimal b3 = new BigDecimal(1.25);
BigDecimal b4 = new BigDecimal(1.05);
System.out.println("BigDecimal() b3 - b4 : " + (b3.subtract(b4)));
}
}

Output :

Float f1 - f2 : 0.20000005
Double d1 - d2 : 0.19999999999999996
BigDecimal("") b1 - b2 : 0.20
BigDecimal() b3 - b4 : 0.1999999999999999555910790149937383830547332763671875

You can see that using float and double for Financial Calculation not provide accurate result.

I also covered BigDecimal different constructor. So based on the output you clear about which constructor use for the Financial Calculations.

Always use BigDecimal with String constructor.