Reputation: 1
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
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
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
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
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:
Upvotes: 0