简体   繁体   中英

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?

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 .

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;
    }
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM