Reputation: 6987
Assuming that performance is not an issue, and knowing that I only want to use ONE type for all the numbers I have in my program, which type will be the correct one to use? I think that BigDecimal
is probably the best option, but I'm not sure of this.
Upvotes: 1
Views: 239
Reputation: 65811
It depends on how you want to use the numbers.
If you are unlikely to need floating point and the numbers aren't going to get too big use int
as the most efficient use of the CPU.
If the numbers might get too big for int
use long
. Uses twice the memory but still cpu efficient.
If too big for long
use BigInteger
. Uses the optimum number of bytes for the number. Breaks when number > about 2^65535 so works for most scenarios. Slower than int
or long
but still seriously fast.
If too big for BigInteger
you're on your own. Perhaps one day ...
If you need float maths float
or double
are good so long as you are working in their range.
For big float maths or a more predictable calculation than double
or float
, use BigDecimal
. Ha sits limitations like BigInteger
but it is rare to be bitten by them.
Beyond that if you are working solely in rationals then you may find a rational number class useful and more accurate than BigDecimal
. This looks ok.
If you are likely to move into irrational territory you may find some of the continued-fractions classes of use. Here is an example.
Upvotes: 7
Reputation: 4496
You are correct. If you only want to use one type (which excludes BigInteger
),
you should use BigDecimal
.
Here is an explanation : The need of BigDecimal
And you can also check this answer: Double vs. BigDecimal?
Upvotes: 1