# Thread: Cost of using BigDecimal vs Floats?

1. Senior Member
Join Date
Apr 2012
Posts
129
Rep Power
0

## Cost of using BigDecimal vs Floats?

After experimenting with floats a bit... i've decided they are just about useless... since almost always i'm needing some sort of precision... and floats continue to let me down.

I'm wondering, is there a real "cost" using something like BigDecimal class every time I would normally use a float? BigDecimal is pretty easy for me to work with so far and the precision is... well, as expected. I assume using a class is going to have some sort of penalty versus using a primitive data type... but is this significant enough for me to worry about?

Thanks for any pointers!

example of basic floats sucking:

Java Code:
```class Sum {
public static void main (String[] args) {
float sum = 0.0f;
boolean isEqualSum = false;

for (int count = 1; count <= 1000; count++) {
sum += 0.1;
}
if (sum == 100) {
isEqualSum = true;
}
System.out.println("The sum of the Double Floating Point is: " + sum);
System.out.println("Is the sum of the Double Floating Point equal to 100? " + isEqualSum);
}
}```

2. ## Re: Cost of using BigDecimal vs Floats?

The cost is in speed and memory, and yes, it can be real in some programs, especially programs that do a lot of number crunching.

3. Senior Member
Join Date
Apr 2012
Posts
129
Rep Power
0

## Re: Cost of using BigDecimal vs Floats?

Is there a way to determine how much extra memeory the BigDecimal and BigInteger classes will consume? I know how to look up what an integer, float, etc will take, but am unsure when it comes to classes... and my small test programs don't consume much besides what the JVM already consumes at runtime...

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: Cost of using BigDecimal vs Floats?

is this significant enough for me to worry about?
It depends on context - ie the program you are writing. Where "It" refers both to the cost of using BigDecimal and the cost of using double (not float).

My advice would be to use double and wait for a problem to emerge. Your code should reflect the realities of using a floating point type (as compared with an infinitely precise mathematical type): eg the loop would be better written as "double sum = 1000 * 0.1;" and the if condition replaced with something that compares sum-100 with a very small value.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•