BigDecimal toString() Method in Java with Examples
The java.math.BigDecimal.toString() method is used to represent the current BigDecimal by which this method is called into String form, using scientific notation if an exponent is needed. It is done by following steps:
- A standard canonical string form of the BigDecimal is created by converting the absolute value of the unscaled value of BigDecimal in base ten using the characters ‘0’ through ‘9’ with no leading zeros except when the value is 0, then single character ‘0’ is used.
- Next, an adjusted exponent is calculated which is one less than adding the number of characters in the converted unscaled value and negated scale value. That is, -scale + (ulength-1), where ulength is the length of the absolute value of the unscaled value in decimal digits (its precision).
- An exponent in character form is then suffixed to the converted unscaled value (perhaps with inserted decimal point). This comprises the letter ‘E’ followed immediately by the adjusted exponent converted to a character form.
- Finally, the entire string is prefixed by a minus sign character ‘-‘ if the unscaled value is less than zero. No sign character is prefixed if the unscaled value is zero or positive.
public String toString()
Parameter: This method do not accepts any parameter.
Return value: This method returns the String representation of this BigDecimal number.
Below programs illustrates the use of toString() method in java
Example 1: Example to convert BigDecimal into String without Scientific notation
Example 2: Example to convert BigDecimal into String with Scientific notation