How to check number of digits from BigDecimal?

Viewed 24616

The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:

First solution:

public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
    BigInteger digits = bigDecVal.toBigInteger();
    BigInteger ten = BigInteger.valueOf(10);
    int count = 0;
    do {
        digits = digits.divide(ten);
        count++;
    } while (!digits.equals(BigInteger.ZERO));
    System.out.println("Number of digits : " + count);
}

First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.

Second solution:

public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
    String string = bigDecVal.toString();
    String[] splitedString = string.split("\\.");
    String[] newVal = splitedString[0].split("");
    int a = newVal.length - 1;
    if (a <= 6) {
        System.out.println("correct size insert into DB: " + a);
    } else {
        System.out.println("Incorrect size insert cancel: " + a);
    }
}

For example, if the value is 999999.9999, the second solution will return newVal.length = 6.

Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.

4 Answers

Because the current answers are not robust enough IMO, Here's my solution. This method will scale a BigDecimal to the given length, but only scales the fractional part. It will throw an Exception if the integer part will be scaled. For my use case this is what I want. Tweak it to your liking.

public static BigDecimal scaleBigDecimalToLength(BigDecimal bigDecimal, int length) throws NumbersUtilException {
  int digitCount = bigDecimal.toPlainString().replaceAll("[.,-]", "").length();
  if (digitCount > length) {
      int scale = bigDecimal.scale();
      int newScale = length - (digitCount - scale);
      if (scale > 0 && newScale >= 0) {
          bigDecimal = bigDecimal
                  .setScale(length - (digitCount - scale), RoundingMode.HALF_UP);
      } else {
          throw new NumbersUtilException(
                  String.format("Cannot scale %s to a length of %s", bigDecimal, length));
    }
  }
  return bigDecimal;
}

scaleBigDecimalToLength(BigDecimal.valueOf(0.0000012345600000), 8) Output: 0.0000012

  1. If you want to ignore the Dot (".") and count. then try this :
        int count = 0;
        BigDecimal bigDecimal = new BigDecimal("123.1000");

        String[] split = bigDecimal.toString()
                .split("\\.");

        for (String element : split) {
            count = count + element.length();
        }

        System.out.println("Total digits are " + count);

Related