-1

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

Alex R
  • 3,139
  • 1
  • 18
  • 28
Loren
  • 320
  • 1
  • 10
  • 25
  • As per the javadocs, the resultant scale will be a.scale - b.scale – Scary Wombat May 29 '20 at 07:41
  • 1
    This may answer your question: https://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values – Alex R May 29 '20 at 07:41
  • No , it does not help. – Loren May 29 '20 at 08:36
  • Does this answer your question? [How to print formatted BigDecimal values?](https://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values) – zforgo May 29 '20 at 10:07
  • It's just a printing issue, not specific for BigDecimals. All you need her is to format your output using `DecimalFormat` class – dgebert May 29 '20 at 14:21

1 Answers1

2

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);
Hemang
  • 1,351
  • 1
  • 10
  • 20