I have a string which has numbers. I have to parse this string and store these numbers in int, float, etc. Accordingly
String str = "100,2.0,-100,19.99,0";
I can do it by Integer.parseInt()
and Float.parseFloat()
after splitting. But I can't do it for negative number. It throws exception java.lang.NumberFormatException
. After searching web I couldn't find any solution for this problem.
So how can I parse a negative integer from string and store into int using j2me api set?
There should be nothing special to parsing negative numbers compared to positive number.
float f = Float.parseFloat("-1.0");
The above code should work perfectly fine.
What might be wrong with your code, is that you're trying to parse a float with the wrong decimal separator. If your locale has .
as decimal separator, the above code is OK. If however your locale has ,
as the decimal separator, the parsing will fail (with a NumberFormatException
).
So make sure you're splitting the original correctly, and that each of the parts after the split are on a valid format (e.g. with the correct decimal separator).
Update:
If you want to know how to parse a number using a specific locale, you could for instance look at this question.