如何在java中将包含逗号的数字字符串解析为整数?

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

有没有办法将它解析为整数?

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

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

结果为265.858 。 但是使用美国语言环境你会得到265858

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

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

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

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

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

如果它是一个数字并且您想要删除分隔符,则NumberFormat将为您返回一个数字。 使用getNumberInstance方法时,请确保使用正确的Locale。

例如,某些Locales将逗号和小数点交换为您可能习惯的内容。

然后只需使用intValue方法返回一个整数。 但是,您必须将整个事物包装在try / catch块中,以解释Parse Exceptions。

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

一种选择是删除逗号:

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

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

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

点击给我的第一件事,假设这是一个数字,是……

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

尝试这个:

 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)));