Javatpoint Logo
Javatpoint Logo

BigDecimal toString() in Java | Convert BigDecimal to String in Java

In Java, BigDecimal is a class that belongs to java.math package and the package belong to java.base module. It extends the Number class and implements the Comparable<BigDecimal> interface. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.

The class provides the various methods for different purposes. In this section, we will discuss commonly used method of the BigDecimal class i.e. toString(). Also, create a Java program to convert BigDecimal to String.

BigDecimal toString() Method

The toString() method of the BigDecimal class provides a canonical representation of the specified BigDecimal. It overrides the toString() method of the Object class. And returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.

Syntax:

The method does not accept any parameter. It returns the string representation of the BigDecimal.

BigDecimal toString() Method Example

BigDecimalExample.java

Output:

234.784300000000001773514668457210063934326171875

In the above program, we have passed a double value as a parameter. Observe that, we do not get the number that we have passed in the constructor as an argument. The reason is double type cannot represent the exact value i.e. 234.7843. So, the value 234.7843 is transform into the closest possible double i.e. 234.784300000000001773514668457210063934326171875. It is the disadvantage of using the toString() method.

Convert BigDecimal to String in Java

To overcome the above problem, there are two ways:

  • Passing value as a String
  • Using valueOf() Method

Passing Value as a String

As, we discussed above if we pass double value in the constructor it returns a large number that close to the specified number. To get the exact number, we have to pass parameter as a string.

Let's see an example.

ConvertBigDecimalToStringExample1.java

Output:

111.987

Using valueOf() Method

The method constructs a BigDecimal based on the canonical representation of the double. The method can be used to convert BigDecimal to String. It internally uses the toString() method. Therefore, using toString() method for conversion will be convenient.

ConvertBigDecimalToStringExample2.java

Output:

23.093451

Next Topic.NET vs Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA