Skip to content
Advertisement

Is there a numerical type (primitive or class) in Java that contains every other numerical type?

  • 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 byte doesn’t contain all short values
  • a short or char doesn’t contain all int values.
  • an int doesn’t contain all long values.
  • a long doesn’t contain all float values.
  • a float doesn’t contain all double values.

The above are evident from the ranges of the respective types.

  • a double doesn’t contain all long values.

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.

  • 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 double


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?)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement