dmbdnr
dmbdnr

Reputation: 334

How to convert any type of Number into BigDecimal without toString()?

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.

Upvotes: 0

Views: 1206

Answers (1)

Bathsheba
Bathsheba

Reputation: 234705

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.

Upvotes: 1

Related Questions