Can any number be converted into a Double in Java ?
If not, is there a Number class that could parse any numerical type
and that would provide basic mathematical operations ?
I have numbers that can be either int, double, float, long, unsigned float or unsigned long. If I could just call them “Number” it will be easier as all I need from them is to operation like equals, greater than, …
Is there a numerical type (primitive or class) in Java that contains every other numerical type?
Starting with the primitive types:
bytedoesn’t contain all
chardoesn’t contain all
intdoesn’t contain all
longdoesn’t contain all
floatdoesn’t contain all
The above are evident from the ranges of the respective types.
doubledoesn’t contain all
This is not quite so obvious. The range of
double is larger than the range of
long, but a
double has only 53 bits of precision. If you do the math, this means that there are numbers (integer values) in the range of
long that cannot have an exact representation as
Long.MAX_VALUE will be one example.
BigInteger does not include values in
double that are not integers.
BigDecimal does not include values that correspond to the ±INF or ±NaN values in
Can any number be converted into a Double in Java?
No, as explained above. Some
long values do not have a corresponding
double value. There there are
If not, is there a Number class that could parse any numerical type and that would provide basic mathematical operations?
If you are prepared to discount INF and NaN values, and use a large enough
precision in the
MathContext, then a
BigDecimal should good enough … within the limits of machine memory and of the implementation.
BigInteger class has an architectural limit; see Is there an upper bound to BigInteger?)