Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse string containing negative number by j2me api?

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?

like image 551
masiboo Avatar asked Feb 02 '12 13:02

masiboo


People also ask

Can parseInt parse negative?

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.

How do you parse a negative value in Java?

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.

Does parseInt work with negative numbers Javascript?

parseInt understands exactly two signs: + for positive, and - for negative.

Can char store negative numbers in Java?

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.


1 Answers

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.

like image 70
Julian Avatar answered Sep 23 '22 05:09

Julian