简体   繁体   中英

How to parse number string containing commas into an integer in java?

I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt() .

Is there any way to parse it into an integer?

Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:

NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")

This results in 265.858 . But using US locale you'll get 265858 :

NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858")

That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.

If these are two numbers - String.split() them and parse two separate strings independently.

在将其解析为int之前,您可以删除它:

int i = Integer.parseInt(myNumberString.replaceAll(",", ""));

If it is one number & you want to remove separators, NumberFormat will return a number to you. Just make sure to use the correct Locale when using the getNumberInstance method.

For instance, some Locales swap the comma and decimal point to what you may be used to.

Then just use the intValue method to return an integer. You'll have to wrap the whole thing in a try/catch block though, to account for Parse Exceptions.

try {
    NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
    ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
    //Handle exception
}

一种选择是删除逗号:

"265,858".replaceAll(",","");

The first thing which clicks to me, assuming this is a single number, is...

String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);

Or you could use NumberFormat.parse , setting it to be integer only.

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String )

Try this:

String x = "265,858 ";
    x = x.split(",")[0];
    System.out.println(Integer.parseInt(x));

EDIT : if you want it rounded to the nearest Integer :

    String x = "265,858 ";
    x = x.replaceAll(",",".");
    System.out.println(Math.round(Double.parseDouble(x)));

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