【问题标题】:BigDecimal. multiply() and divide() methods return hexadecimal number. Why?大十进制。 multiply() 和 divide() 方法返回十六进制数。为什么?
【发布时间】:2021-08-31 01:24:12
【问题描述】:

这是我的代码:

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

【问题讨论】:

    标签: java bigdecimal


    【解决方案1】:

    这不是十六进制,而是 the scientific notationtoString() 方法评估的:

    返回此BigDecimal 的字符串表示形式,如果需要指数,则使用科学记数法。

    E 字母表示数字的指数。

    一般如果要格式化十进制数,可以使用java.text.DecimalFormat

    【讨论】:

    【解决方案2】:

    在您的情况下,使用 toString 方法,如果需要,它将使用指数字段。

    如果您不想要带有指数字段的字符串表示,您可以使用toPlainString

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2015-06-25
      • 2022-11-16
      • 2020-03-28
      相关资源
      最近更新 更多