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

Using double and float for exact calculation

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)));
}
}
Float f1 - f2 : 0.20000005
Double d1 - d2 : 0.19999999999999996
BigDecimal("") b1 - b2 : 0.20
BigDecimal() b3 - b4 : 0.1999999999999999555910790149937383830547332763671875

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

20 Tips on Courses, Websites, and Channels to Learn Excel

Love and Hate relationship with Microsoft

Progressive Delivery, Kubernetes, and 3D Chess

Spring — Web Container | Code Factory

Inner Sourcing: What’s this?

Java — A quick overview

OBJECT COMPOSITION; THE HOLY GRAIL IN SOFTWARE DEVELOPMENT.

Kubernetes vs OpenShift

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

InjectIntoKeyValue in Eclipse Collections

Functional Interfaces in Java

Java Virtual Machine

Reactive Programming : Project-Reactor / Rx-Java / Java 9 Reactive Flow