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?
As the name suggests, parseInt() is the core method to convert String to int in Java. parseInt() accept a String which must contain decimal digits and the first character can be an ASCII minus sign (-) to denote negative integers.
String binary = Integer. toBinaryString(-1); // convert -1 to binary // 11111111 11111111 11111111 11111111 (two's complement) int number = Integer. parseInt(binary, 2); // convert negative binary back to integer System.
parseInt understands exactly two signs: + for positive, and - for negative.
One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With