What is NumberUtils.createBigDecimal() in Java?
createBigDecimal() is a NumberUtils class that is used to convert a string to a BigDecimal datatype. If the string cannot be converted to a BigDecimal value, then NumberFormatException will be thrown by the method.
How to import NumberUtils
The definition of NumberUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the NumberUtils class as follows:
import org.apache.commons.lang3.math.NumberUtils;
Syntax
public static BigDecimal createBigDecimal(final String str)
Parameters
final String str: The string to convert.
Return value
This method returns the converted BigDecimal value.
Code
The code below shows how the NumberUtils.createBigDecimal() method works in Java.
import org.apache.commons.lang3.math.NumberUtils;public class Main{public static void main(String[] args){// Example 1String valueToConvert = "234323232.232123";System.out.printf("NumberUtils.createBigDecimal(%s) = %s", valueToConvert, NumberUtils.createBigDecimal(valueToConvert));System.out.println();// Example 2valueToConvert = "234323wrf";System.out.printf("NumberUtils.createBigDecimal(%s) = %s", valueToConvert, NumberUtils.createBigDecimal(valueToConvert));System.out.println();}}
Output
The output of the code will be as follows:
NumberUtils.createBigDecimal(234323232.232123) = 234323232.232123
Exception in thread "main" java.lang.NumberFormatException: Character w is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:518)
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:401)
at java.base/java.math.BigDecimal.<init>(BigDecimal.java:834)
at org.apache.commons.lang3.math.NumberUtils.createBigDecimal(NumberUtils.java:1004)
at Main.main(Main.java:13)
Explanation
Example 1
string value = 234323232.232123
The method returns 234323232.232123 as the conversion is successful.
Example 2
string value = 234323wrf
The method throws NumberFormatException as the conversion is unsuccessful.