1

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

Ansar1437
  • 21
  • 5

2 Answers2

6

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.

M A
  • 71,713
  • 13
  • 134
  • 174
  • Thank you for your response! Is there any way to transform this number to decimal form? – Ansar1437 Jun 15 '21 at 07:52
  • @Ansar1437 Have a look at https://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values and the DecimalFormat class. – M A Jun 15 '21 at 08:01
4

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());
TT.
  • 15,774
  • 6
  • 47
  • 88