Home > database >  Java - I am trying to check for the data type BigDecimal has decimal points including the zeros
Java - I am trying to check for the data type BigDecimal has decimal points including the zeros

Time:09-02

//Example : 100 not decimal, 100.00 is a decimal, 100.01 is a decimal

The problem is I am not able to identify between 100 and 100.00 as both says it doesn't have decimal

Note : it should work for any positive scenarios

CodePudding user response:

Try scale():

https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scale()

import java.math.BigDecimal;

public class Big {
    public static void main(String[] args) {
     BigDecimal a = BigDecimal.valueOf(100);
     System.out.println("Scale of a is " a.scale());

     BigDecimal b = BigDecimal.valueOf(100.0);
     System.out.println("Scale of b is " b.scale());
    }
}

Output:

Scale of a is 0
Scale of b is 1

CodePudding user response:

Here is code that checks for a decimal dot in a BigDecimal converted to a string. It is not checking if there are digits after that.

To check if there is a digit after then dot then check if (indexOfDot>1)

Reference: Determine Number of Decimal Place using BigDecimal

import java.math.BigDecimal;

class Main{
public static void main(String[] args) {
    BigDecimal n1 = new BigDecimal("100");   
    BigDecimal n2 = new BigDecimal("100.00");
           
    boolean a = isBigDecimalHavingDecimalDot(n1);
    boolean b = isBigDecimalHavingDecimalDot(n2);
}

static boolean isBigDecimalHavingDecimalDot(BigDecimal num) {
    String numString = num.toPlainString();
    int indexOfDot = numString.indexOf(".");
    if (indexOfDot > 0) {
        System.out.println("Has a decimal dot");
        return true;
    } else {
        System.out.println("Does not have a decimal dot");
        return false;
    }  
}
}
  • Related