Login with  Log in with facebook
Hiring Manager? SIGN UP HERE
What's wrong with storing money using float or double in java.
Rishi Yadav
08/11/2011 at 09:43
4 Answers


Rishi Yadav
08/13/2011 at 00:07


Let's do it with an example. 


import java.math.BigDecimal;


public class MoneyTest {


public static void main(String... args) {


float fIncrement = 0.1f;

float fTotal = 0.0f;

BigDecimal bdTotal = new BigDecimal(0.0);

BigDecimal bdIncrement = new BigDecimal(0.1);

for (int i = 0; i < 100000000; i++) {

fTotal += fIncrement;

bdTotal = bdTotal.add(bdIncrement);


System.out.println("float addition is" + fTotal);

System.out.println("BD addition is" + bdTotal);






and Here's the result

float addition is9998.557

BD addition is10000.0000000000005551115123125782702118158340454101562500000

Though BigDecimal is not perfect float introduces a lot of error in financial calculalations. 

Rishi Yadav
08/13/2011 at 18:44


using money amount and putting it to double is not exact, you will have precision loss. there are two ways to handle this:

1) use BigDecimal.

2) put the value in a long format removing the decimal point. the add, subtract or multiply using long. and to get the final answer divide the long value with 100 and store it to double.

Kokok Tolentino
08/19/2011 at 14:45


We have a method in the Math class called ulp, which returns the positive distance between the float or double with the next possible representable float or double. This distance is vary large as the value increases.

eg if you try on a float value of 123456789f

The value is 8.0. so you can understand that the loss of precision is very high as the magnitude of the floating point value increases.


Pravin Jain
08/27/2011 at 11:01

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *