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.

- 6,907
- 4
- 24
- 47
-
3I am afraid this is a primarily opinion based question, and probably too broad to answer. BigDecimal is robust enough to handle almost anything your likely to throw at it, but we have no idea what your application does or needs to do. – Rudi Kershaw Feb 28 '14 at 14:06
-
you answeared yourself - BigDecimal – Leos Literak Feb 28 '14 at 14:07
-
Maybe you functions should be generic enough to work with any kind of number instead of working with "the" number type that doesn't exist. BigDecimal can't even represent 1/3 correctly, let alone pi, sqrt(-1), a quaternion or most surreal numbers. – Niklas B. Feb 28 '14 at 14:09
-
Why do you need only **one** type for representing numbers? – rpax Feb 28 '14 at 14:12
-
3String. Can represent everything. :-) – Seelenvirtuose Feb 28 '14 at 14:22
-
@Seelenvirtuose that's very hardcore, don't you think? +1 – rpax Feb 28 '14 at 14:24
-
1Write the code to accept `java.lang.Number` as input. Then the caller who knows the number can choose the optimal number type for the value, which might be `BigDecimal` but doesn’t have to. – Holger Feb 28 '14 at 15:39
2 Answers
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.

- 64,482
- 16
- 119
- 213
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?