40

で265,858NumberFormatExceptionを解析しようとすると取得しInteger.parseInt()ます。

それを整数に解析する方法はありますか?

4

7 に答える 7

80

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.

于 2012-08-15T16:44:13.463 に答える
21

You can remove the , before parsing it to an int:

int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
于 2012-08-15T16:43:36.493 に答える
12

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
}
于 2012-08-15T16:51:50.293 に答える
4

One option would be to strip the commas:

"265,858".replaceAll(",","");
于 2012-08-15T16:42:55.947 に答える
3

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);
于 2012-08-15T16:44:00.700 に答える
2

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)

于 2012-08-15T16:46:39.027 に答える
0

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)));
于 2012-08-15T16:43:20.440 に答える