Convert Java Number to BigDecimal : best way

user1721413 picture user1721413 · Apr 25, 2013 · Viewed 98.7k times · Source

I am looking for the best way to convert a Number to a BigDecimal.

Is this good enough?

Number number;
BigDecimal big = new BigDecimal(number.toString());

Can we lose precision with the toString() method ?

Answer

david99world picture david99world · Apr 25, 2013

This is fine, remember that using the constructor of BigDecimal to declare a value can be dangerous when it's not of type String. Consider the below...

BigDecimal valDouble = new BigDecimal(0.35);
System.out.println(valDouble);

This will not print 0.35, it will infact be...

0.34999999999999997779553950749686919152736663818359375

I'd say your solution is probably the safest because of that.