0

I'm using now this method, to execute addition on any type of Number:

public <T extends Number> CustomNumber add(T a, T b) {
    BigDecimal numberA = new BigDecimal(b.toString());
    BigDecimal numberB = new BigDecimal(a.toString());
    return new CustomNumber<>(numberA.add(numberB));
}

I'm using BigDecimal, because as far as I know this is the best solution, to execute precize calculations. How can I change this method, to achieve the same result without the toString() method? CustomNumber is the class I'm using to store numeric values.

dmbdnr
  • 334
  • 3
  • 19

1 Answers1

1

I wouldn't risk it, particularly if you want to construct a BigDecimal from a floating point type.

In the most general case, construction from a String is the safest way. Always take the requisite amount of care with locale-dependent decimal separators.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483