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, …
Advertisement
Answer
Is there a numerical type (primitive or class) in Java that contains every other numerical type?
No.
Starting with the primitive types:
- a
bytedoesn’t contain allshortvalues - a
shortorchardoesn’t contain allintvalues. - an
intdoesn’t contain alllongvalues. - a
longdoesn’t contain allfloatvalues. - a
floatdoesn’t contain alldoublevalues.
The above are evident from the ranges of the respective types.
- a
doubledoesn’t contain alllongvalues.
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 double values. Long.MAX_VALUE will be one example.
What about BigInteger and BigDecimal.
BigIntegerdoes not include values indoublethat are not integers.BigDecimaldoes not include values that correspond to the ±INF or ±NaN values indouble
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 BigInteger and BigDecimal values.
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.
(The current BigInteger class has an architectural limit; see Is there an upper bound to BigInteger?)