简体   繁体   English

如何在除以 BigDecimal 时保持尾随零

[英]How to keep trailing zeros when dividing a BigDecimal

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.我有一个要求,我需要将一个BigDecimal数除以 100,并显示在不删除尾随零的情况下出现的确切数量。 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 Output: 26.0982预期: 26.098200

What you want is formatting as those 0 does not add to value.您想要的是格式化,因为那些 0 不会增加价值。 You can use this and you will get desired output.您可以使用它,您将获得所需的 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.其他选项,如果您总是想除以 100,您可以移动小数点。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM