I have to convert String into float I am doing it like this :
float[] iLongs = new float[mLongs.length];
for(int i = 0; i < iLongs.length ; i++){
iLongs[i] = Float.valueOf(mLongs[i]).floatValue();
}
But it 开发者_如何学运维throws numberformat exception
But if I use the same function outside any loop it works. What to do ?
The code looks fine, which leads me to suspect that it's a data issue. You need to verify that every index for mLongs contains a String that is actually valid as a float, how you do that is up to you.
Alternative code :
class StringToFloat {
public static void main (String[] args) {
// String s = "hello"; // do this if you want an exception
String s = "100.00";
try {
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
}
}
// Output :float f = 100.0
There is nothing wrong with your code. Exception happend because String is not a Float and cannot be parsed. Most common mistake - , instead of .
You are correct syntactically. I think problem is in mLongs. It might contain some alphabetic character.
精彩评论