BigDecimal. multiply() and divide() methods return hexadecimal number. Why?

Viewed 97

Here is my code:

public class Test1 {
    public static void main(String[] args) {
        BigDecimal wallet = new BigDecimal("0.0");
        BigDecimal productPrice = new BigDecimal("0.01");

        for (int i = 1; i <= 5; i++) {
            wallet = wallet.multiply(productPrice);
        }
        System.out.println(wallet);
    }
} 

Result: 0E-11
I have a question. Why am I getting the result in the hexadecimal number system and not in decimal? Like this: 2.45

2 Answers

That's not a hexadecimal, it's the scientific notation as evaluated by the toString() method:

Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.

The E letter denotes the exponent of the number.

In general if you want to format a decimal number, you can use java.text.DecimalFormat.

In your case, the method toString is used which will use an exponent field if needed.

You can use toPlainString if you do not want a string representation with an exponent field.

System.out.println(wallet.toPlainString());
Related