# Cost of using BigDecimal vs Floats?

• 08-19-2012, 07:45 AM
SnakeDoc
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:

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);         } }```
• 08-19-2012, 07:48 AM
Fubarable
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.
• 08-19-2012, 08:03 AM
SnakeDoc
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...
• 08-19-2012, 09:05 AM
pbrockway2
Re: Cost of using BigDecimal vs Floats?
Quote:

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.