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

Donate : Link

Medium Blog : Link

Applications : Link

Using double and float for exact calculation

This is one of common mistake Java programmer make until they are familiar with BigDecimal class. When we learn Java programming we have been told that use float and double to represent decimal numbers its not been told that result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation.

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s