如何在除法运算时保留 BigDecimal 的尾部零。

huangapple go评论66阅读模式
英文:

How to keep trailing zeros when dividing a BigDecimal

问题

我有一个需求,在这个需求中我需要将一个 `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`
英文:

I have a requirement where I need to divide one BigDecimal number by 100 and show the exact amount that comes up without removing trailing zeros. But zeros are getting trimmed by default. How do I prevent that?

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


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

Output: 26.0982
Expected: 26.098200

答案1

得分: 2

你想要的是将这些 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);
英文:

What you want is formatting as those 0 does not add to value. You can use this and you will get desired output.


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

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

Other option if you always want to divide by 100, you can just shift the decimal. When you do that, the precision remains the same. In that case the new code to try is


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


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

huangapple
  • 本文由 发表于 2020年5月29日 15:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/62080924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定