I want to count the number after the decimal point.
input(Float) | output(int) |
---|---|
0.0 | 0 |
1.0 | 0 |
0.1 | 1 |
11.1 | 1 |
0.001 | 3 |
public int getPrecision(Float val){
//In Java, the method of converting from Float to int is a lot of useless processing, so count it as a character string.
String str = String.valueOf(val);
//The end of the sentence".0"And".00000"All those ending with are 0 digits
if(str.matches("^.*\\.0+$")){
return 0;
}
int index = str.indexOf(".");
return str.substring(index + 1).length();
}
I can do what I want to do.
First, the regular expression part
str.matches("\\.0+$")
When I wrote it as, the output became strange.
Input 0.0 Output 1 ← Wrong
Input 0.1 Output 1 ← Correct
that?
When I debug it,
"0.0".matches("\\.0+$")
//result:false
that? Does not match
Actually, this code was synonymous with the following code.
"0.0".matches("^\\.0+$$")
//result:false
When using the String.matches method in java, use a regex that includes ^
and $
// \\.0+$When you want to use the regular expression of. .. ..
"0.0".matches("^.*\\.0+$")
//result:true
http://d.hatena.ne.jp/kakkun61/20100104/1262605869
Recommended Posts