0

I have two Numbers they maybe integer float or double, how to add them in java, Number object cannot add each other.

I can only test there type(class) and convert one by one, it's ugly (lots of if else) and obscure, any better idea?

jamee
  • 553
  • 1
  • 5
  • 25

2 Answers2

2

You can invoke Number.doubleValue() and add:

Number n1 = new Double(10.3d);
Number n2 = new Integer(12);
System.out.println(n1.doubleValue() + n2.doubleValue());
olsli
  • 831
  • 6
  • 8
0

If precision loss is acceptable, you can add their double (or even BigDecimal) values:

double result = a.doubleValue() + b.doubleValue();

Otherwise, you will have implement all cases (which you can do only do for common types, as Number is an abstract class).

To be honest, this is very likely to be a sign of bad conception.

nicoulaj
  • 3,463
  • 4
  • 27
  • 32