简体   繁体   中英

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?

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 (eg 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 .

I had a similar problem today and the problem was that the minus sign in the input string was actually an m-dash character. That was nasty! So that's definitely worth checking.

Clarification: Well, I thought you wanted to distinguish between int and float. Just Float.parseFloat(..) will do as well, Not need to of contains test. :) Misread!

    String str = "100,2.0,-100,19.99,0";
    String[] ns = str.split(",");
    for(String s: ns){
        if(s.contains("."))
            System.out.println("Float: "+ Float.parseFloat(s));
        else
            System.out.println("Int: "+ Integer.parseInt(s));
    }

Output

Int: 100
Float: 2.0
Int: -100
Float: 19.99
Int: 0

Update so this:

    String str = "100,2.0,-100,19.99,0";
    String[] ns = str.split(",");
    for(String s: ns)
            System.out.println("Float: "+ Float.parseFloat(s));

also works.

You can split by the delimiter ',' and check if there is a negative sign so multiply the number by -1 or do it by

Float parseFloat(str);

It will work properly.

Thats strange, possibly its an encoding issue. Integer.parseInt() should work with positive and negative numbers as well as other similar methods (Float.parse...). What you can do is always to check for a sign '-' or '+' before you parse and assign the sign after the parsing. This method has its advantage, as if you receive number with '+' sign the standard Integer.parseInt won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM