Riday Bhatrai
Riday Bhatrai

Reputation: 1

How can I use an if statement to check if a number only has two digits after the decimal in java?

I'm currently only checking to see if a number is a float using this

public boolean checkStringFloat(String str) {
    try{
        Float.parseFloat(str);
    }
    catch(NumberFormatException e){
        return false;
    }
    return true;
}

but I want to use an if statement to check if it is a decimal with two digits. So for instance numbers like: 6.24, 5.28,13242.31, would be allowed but numbers like: 5.234, 1, 0, 4.235 would not be allowed. How can I do this?

Upvotes: 0

Views: 554

Answers (4)

Srikanth Chakravarthy
Srikanth Chakravarthy

Reputation: 96

BigDecimal#scale

As @TimBiegeleisen said, use BigDecimal with its scale method.

public boolean checkStringFloat(String str) {
    BigDecimal bigDecimal = new BigDecimal(str);
    if(bigDecimal.scale() == 2) {
       return true;
    } else {
       return false;
    }
}

Upvotes: 1

Basil Bourque
Basil Bourque

Reputation: 338875

Split the string, and check the length of second part.

"13242.31".split( "\\." )[ 1 ].length() == 2 

See this code run live at IdeOne.com.

boolean hasTwoDigitDecimalFraction = "13242.31".split( "\\." )[ 1 ].length() == 2 ;
System.out.println( hasTwoDigitDecimalFraction ) ;

true

Validate your inputs by calling String#contains to be sure it has a FULL STOP character. And check the length of the array from the .split to be sure it has exactly two elements.

Be aware that in many parts of the world such inputs would use a COMMA rather than a FULL STOP character as the delimiter: 13242,31.

Upvotes: 2

TheSj
TheSj

Reputation: 386

You could find the length of the string after the "." using .substring().

if (str.substring(str.indexOf(".")).length() == 2) return true;
else return false;

I don't have an editor with me, but this should work fine. If it doesn't, try adding a 1 to the indexOf.

Upvotes: 0

greyWolf
greyWolf

Reputation: 321

My general idea is as follows, just for reference Start with a simple end-to-zero operation on the string String indexOf('.') returns i, len= string.length and the following will happen:

  1. i=-1 , it means that there is no decimal point
  2. i=len-2 , There are two characters after the decimal point, so you only need to determine whether the two characters is a number
  3. i>=len || i<len-2 Obviously, not

Upvotes: 0

Related Questions