有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java BigDecimal。multiply()和divide()方法返回十六进制数。为什么?

这是我的代码:

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);
    }
} 

结果:0E-11
我有个问题。为什么我得到的结果是十六进制而不是十进制?像这样:2.45


共 (2) 个答案

  1. # 1 楼答案

    在您的例子中,使用方法^{},如果需要,它将使用指数字段

    如果不想使用带有指数字段的字符串表示,可以使用^{}

    System.out.println(wallet.toPlainString());
    
  2. # 2 楼答案

    这不是十六进制,而是^{}方法计算的the scientific notation

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

    字母E表示数字的指数

    一般来说,如果要格式化十进制数,可以使用^{}