1. Overview
In this tutorial, we'll cover many ways of converting String to BigDecimal in Java.
2. BigDecimal
BigDecimal represents an immutable arbitrary-precision signed decimal number. It consists of two parts:
- Unscaled value – an arbitrary precision integer
- Scale – a 32-bit integer representing the number of digits to the right of the decimal point
For example, the BigDecimal 3.14 has an unscaled value of 314 and a scale of 2.
If zero or positive, the scale is the number of digits to the right of the decimal point.
If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. Therefore, the value of the number represented by the BigDecimal is – (Unscaled value × 10-Scale).
The BigDecimal class in Java provides operations for basic arithmetic, scale manipulation, comparison, format conversion, and hashing.
Moreover, we use BigDecimal for high-precision arithmetic, calculations requiring control over the scale, and rounding off behavior. One such example is calculations involving financial transactions.
We can convert a String into BigDecimal in Java using one of the below methods:
- BigDecimal(String) constructor
- BigDecimal.valueOf() method
- DecimalFormat.parse() method
Let's discuss all of them below.
3. BigDecimal(String)
The easiest way to convert String to BigDecimal in Java is to use BigDecimal(String) constructor:
BigDecimal bigDecimal = new BigDecimal("123");
assertEquals(new BigDecimal(123), bigDecimal);
4. BigDecimal.valueOf()
We can also convert String to BigDecimal by using the BigDecimal.valueOf(double) method.
It is a two-step process. The first step is to convert the String to Double. The second step is to convert Double to BigDecimal:
BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf("123.42"));
assertEquals(new BigDecimal(123.42).setScale(2, BigDecimal.ROUND_HALF_UP), bigDecimal);
5. DecimalFormat.parse()
When a String representing a value has a more complex format, we can use a DecimalFormat.
For example, we can convert a decimal-based long value without removing non-numeric symbols:
BigDecimal bigDecimal = new BigDecimal(10692467440017.111).setScale(3, BigDecimal.ROUND_HALF_UP);
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string value
BigDecimal parsedStringValue = (BigDecimal) decimalFormat.parse("10,692,467,440,017.111");
assertEquals(bigDecimal, parsedStringValue);
The DecimalFormat.parse method returns a Number, which we convert to a BigDecimal number using the setParseBigDecimal(true);
Usually, the DecimalFormat is more advanced than we require. Thus, we should favor the new BigDecimal(String) or the BigDecimal.valueOf() instead.
6. Invalid Conversions
Java provides generic exceptions for handling invalid numeric Strings.
Notably, new BigDecimal(String), BigDecimal.valueOf(), DecimalFormat.parse throw a NullPointerException when we pass null:
@Test(expected = NullPointerException.class)
public void givenNullString_WhenBigDecimalObjectWithStringParameter_ThenNullPointerExceptionIsThrown() {
String bigDecimal = null;
new BigDecimal(bigDecimal);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenValueOfDoubleFromString_ThenNullPointerExceptionIsThrown() {
BigDecimal.valueOf(Double.valueOf(null));
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenDecimalFormatOfString_ThenNullPointerExceptionIsThrown()
throws ParseException {
new DecimalFormat("#").parse(null);
}
Likewise, new BigDecimal(String), BigDecimal.valueOf() throw a NumberFormatException when we pass an invalid String that cannot be parsed to a BigDecimal (such as &):
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenBigDecimalObjectWithStringParameter_ThenNumberFormatExceptionIsThrown() {
new BigDecimal("&");
}
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenValueOfDoubleFromString_ThenNumberFormatExceptionIsThrown() {
BigDecimal.valueOf(Double.valueOf("&"));
}
Lastly, DecimalFormat.parse throws a ParseException when we pass an invalid String:
@Test(expected = ParseException.class)
public void givenInalidString_WhenDecimalFormatOfString_ThenNumberFormatExceptionIsThrown()
throws ParseException {
new DecimalFormat("#").parse("&");
}
7. Conclusion
In conclusion, Java provides us multiple methods to convert String to BigDecimal values.
In general, we recommend using the new BigDecimal(String) for converting String to BigDecimal in java.
As always, the code used in this article can be found over on GitHub.
The post Converting String to BigDecimal in Java first appeared on Baeldung.