How to Convert String Into BigDecimal in Java

In Java, converting between BigDecimal and String is a common operation, especially when dealing with precise decimal numbers. Java provides convenient methods to perform this conversion. In this blog post, we will explore how to convert a BigDecimal to a String and vice versa. 

Convert BigDecimal to String

To convert a BigDecimal to a String, you can use the toString() method.

Example:
import java.math.BigDecimal;

public class BigDecimalToStringExample {
    public static void main(String[] args) {
        BigDecimal bigDecimalValue = new BigDecimal("123456.789");
        String numberString = bigDecimalValue.toString();

        System.out.println("BigDecimal: " + bigDecimalValue);
        System.out.println("String: " + numberString);
    }
}

Output:

BigDecimal: 123456.789
String: 123456.789

Convert String to BigDecimal

To convert a String to a BigDecimal, you can use the BigDecimal(String) constructor. 

Example:
import java.math.BigDecimal;

public class StringToBigDecimalExample {
    public static void main(String[] args) {
        String numberString = "98765.4321";
        BigDecimal bigDecimalValue = new BigDecimal(numberString);

        System.out.println("String: " + numberString);
        System.out.println("BigDecimal: " + bigDecimalValue);
    }
}

Output:

String: 98765.4321
BigDecimal: 98765.4321

Conclusion

In this blog post, we have seen how to convert a BigDecimal to a String using the toString() method and how to convert a String to a BigDecimal using the BigDecimal(String) constructor. These conversions are useful when working with precise decimal values, such as currency or financial calculations, where accuracy is essential. BigDecimal provides the necessary precision and rounding capabilities to perform arithmetic operations with decimal numbers reliably.

Comments