【问题标题】:How to keep trailing zeros when dividing a BigDecimal如何在除以 BigDecimal 时保持尾随零
【发布时间】:2020-09-16 17:25:20
【问题描述】:

我有一个要求,我需要将一个 BigDecimal 数字除以 100,并在不删除尾随零的情况下显示出现的确切数量。但是默认情况下会修剪零。我该如何预防?

BigDecimal endDte = new BigDecimal("2609.8200");
BigDecimal startDte = new BigDecimal("100");


BigDecimal finalPerformance = endDte.divide(startDte);
System.out.println(finalPerformance.toString());

输出:26.0982 预期:26.098200

【问题讨论】:

标签: java bigdecimal zero divide


【解决方案1】:

您想要的是格式化,因为那些 0 不会增加价值。你可以使用它,你会得到想要的输出。


        BigDecimal endDte = new BigDecimal("2609.8200");
        BigDecimal startDte = new BigDecimal("100");

        BigDecimal finalPerformance = endDte.divide(startDte);
        System.out.printf("%2.6f%n", finalPerformance);

如果您总是想除以 100,则可以选择其他选项,只需移动小数点即可。当你这样做时,精度保持不变。在这种情况下,要尝试的新代码是


        BigDecimal endDte = new BigDecimal("2609.8200");
        //BigDecimal startDte = new BigDecimal("100");


        BigDecimal finalPerformance = endDte.movePointLeft(2);
        System.out.println(finalPerformance);

【讨论】:

  • 如果值是 2609.82001 则它从末尾删除 1 则不工作。
  • 我所做的只是格式化。我所说的只是打印小数点后 6 位。
  • movePointLeft 是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2013-03-02
  • 2014-09-13
相关资源
最近更新 更多