Which data type would you choose for storing currency values like Trading Price in Java?

By | November 26, 2019

In this post we will talk and learn  Which data type would you choose for storing currency values like Trading Price ? What is your opinion about Float, Double and BigDecimal data types ?

Let’s see how double data type works for financial calculation

Sample output of above program:

Total Amount = 20.19999999999996

The output suppose to be 20.20 (20 dollars and 20 cents), but because of floating point calculation made it 20.1999999999..

Let’s see now how BigDecimal data type works for financial calculation

Sample output::

Total Amount = 20.2

How  we format BigDecimal Value without getting exponentiation in the result & Strip the trailing zeros?
We may get exponentiation in the calculation result if we do not follow some best practices while using Bigdecimal data type. Below  example is the code snippet which shows a good usage  of handling the calculation result using Bigdecimal.

Sample Output:

0.2000
Value = 0.2

You may also like:

Why Java is not 100% Object-oriented language?
What are the differences between 32-bit and 64-bit versions of Java?
Can we call static method with null object?
Can we override static method in Java?
What will be the output of following java program?
What is the difference Between java.util.Date and java.sql.Date in Java ?
What is difference between using Serializable & Externalizable Interfaces in Java?

That’s all about Which data type would you choose for storing currency values like Trading Price in Java ?
If you have any feedback or suggestion please feel free to drop in blow comment box. 

Leave a Reply

Your email address will not be published.