40

NumberFormatException当我尝试解析 265,858 时,我得到了Integer.parseInt().

有没有办法把它解析成整数?

4

7 回答 7

80

这个逗号是小数分隔符还是这两个数字?在第一种情况下,您必须向Locale使用NumberFormat逗号作为小数分隔符的类提供:

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

这导致265.858. 但是使用美国语言环境你会得到265858

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

那是因为在法国,他们将逗号视为小数分隔符,而在美国则将逗号视为分组(千位)分隔符。

如果这些是两个数字 -String.split()它们并独立解析两个单独的字符串。

于 2012-08-15T16:44:13.463 回答
21

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

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

如果它是一个数字并且您想删除分隔符,NumberFormat将返回一个数字给您。只需确保在使用该getNumberInstance方法时使用正确的语言环境。

例如,某些语言环境将逗号和小数点交换为您可能习惯的。

然后只需使用该intValue方法返回一个整数。但是,您必须将整个内容包装在 try/catch 块中,以解决 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

一种选择是去掉逗号:

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

假设这是一个数字,首先点击我的是......

String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
于 2012-08-15T16:44:00.700 回答
2

或者您可以使用NumberFormat.parse,仅将其设置为整数。

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

尝试这个:

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

编辑:如果你希望它四舍五入到最接近的整数:

    String x = "265,858 ";
    x = x.replaceAll(",",".");
    System.out.println(Math.round(Double.parseDouble(x)));
于 2012-08-15T16:43:20.440 回答