Search code examples
javabigdecimalzerodivide

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. 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


Solution

  • 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);