1. Using Constructor of Big Decimal class [Recommended]
2. Using BigDecimal.valueOf() method
Read Also: Convert String to Boolean in Java
1. Using Constructor of Big Decimal
This is the easiest way to convert String to BigDecimal in java. Just use BigDecimal(String) constructor.BigDecimal obj = new BigDecimal(String);
The above line will do the job. You can find the example below:
import java.math.*; public class JavaHungry { public static void main(String args[]) { String str = "123.45"; // Using BigDecimal(String) constructor BigDecimal num = new BigDecimal(str); // Printing BigDecimal value System.out.println("Converted String to BigDecimal : " + num); } }
Output:
Converted String to BigDecimal : 123.45
Note: String passed in a constructor should be a valid number otherwise NumberFormatException will be thrown.
2. Using BigDecimal.valueOf() method
Convert String to BigDecimal by using 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, using BigDecimal.valueOf(double) method. As shown in the example below:
import java.math.*; public class JavaHungry { public static void main(String args[]) { String str = "123.45"; // Converting String to Double Double obj = new Double(str); // Converting Double to BigDecimal BigDecimal num = BigDecimal.valueOf(obj); // Printing BigDecimal value System.out.println("Converted String to BigDecimal: " + num); } }
Output:
Converted String to BigDecimal: 123.45
Note: BigDecimal.valueOf(double) is a static method. You do not need to create a BigDecimal object to access it.
That's all for the day. Please mention in comments in case you have any questions related to convert String to BigDecimal in java with examples.