Search code examples
javabigdecimal

Possible to find out if a BigDecimal only has zeros recurring after a certain point?


Specifically, I want to know if it's possible to determine if everything after 2 decimal points will always be a zero.

For example where this is the case:

    BigDecimal m1 = new BigDecimal("15");
    BigDecimal m2 = new BigDecimal("2");
    BigDecimal m3 = m1.divide(m2, 5, BigDecimal.ROUND_CEILING);
m3 is equal to 7.50000 (and there will still be 0s even if you increase the precision)

An example where this is not the case

    BigDecimal m1 = new BigDecimal("11.24");
    BigDecimal m2 = new BigDecimal("6");
    BigDecimal m3 = m1.divide(m2, 5, BigDecimal.ROUND_CEILING);
m3 is equal to 1.87334

Another possible scenario where this will not be the case (can't think of division values) is when

 m3 is equal to 7.50000001

Thank you for your help (and I apologise if the answer is straightforward/simple!)


Solution

  • Use setScale() to trim off everything after 2 decimal points, and compareTo() to see if it's mathematically equal to the original value:

    class BigDecimalExperiment {
        static boolean isEverythingAfterTwoDigitsZero(BigDecimal bd) {
            return (bd.compareTo(bd.setScale(2, RoundingMode.DOWN)) == 0);
        }
    
        public static void main(String[] args) {
            List<BigDecimal> values = Arrays.asList(
                    new BigDecimal("7.5"),
                    new BigDecimal("7.50000"),
                    new BigDecimal("7.50000001"),
                    new BigDecimal("75.01"),
                    new BigDecimal(75.01),
                    new BigDecimal("75.0100000"),
                    new BigDecimal("75.0100001")
            );
            for (BigDecimal value : values) {
                System.out.printf("%s\t%s%n", isEverythingAfterTwoDigitsZero(value), value);
            }
        }
    }
    

    prints

    true    7.5
    true    7.50000
    false   7.50000001
    true    75.01
    false   75.0100000000000051159076974727213382720947265625
    true    75.0100000
    false   75.0100001