How to Convert BigDecimals to Strings in Java - dummies

How to Convert BigDecimals to Strings in Java

By Doug Lowe

In Java, the BigDecimal class has several methods that let you convert BigDecimal values to strings, doubles, or integers. Take a look at the following for a list of the conversion methods.

Method Explanation
double doubleValue() Returns the value of this BigDecimal
as a double.
int intValue() Returns the value of this BigDecimal
as an int.
long longValue() Returns the value of this BigDecimal
as a long.
String toPlainString() Returns a string representation of this BigDecimal that doesn’t use scientific
notation.
String toString() Returns a string representation of this BigDecimal that uses scientific notation if
necessary.

In most cases, the only reason to convert a BigDecimal to a double is so you can use the double with the NumberFormat class to format the value for output. As long as you don’t do any intermediate calculations with the double, you won’t encounter any accuracy errors unless the numbers are large. (You start to run into problems at about 13 digits.)

Here’s a snippet of code that converts a BigDecimal object named salesTax to a double and uses it with the NumberFormat class:

NumberFormat cf = NumberFormat.getCurrencyInstance();
double taxD = salesTax.doubleValue();
System.out.println(cf.format(taxD));

You can also use the toString method to format a BigDecimal as a string, but this method doesn’t add commas or any other formatting niceties. Note also that this method sometimes switches to exponential notation if the number is large. To avoid that, you can use the toPlainString method instead.