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 ?
Advertisement
Answer
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.