英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论