当我试图使用Integer.parseInt()
解析265,858时,出现了NumberFormatException
错误。
有没有什么方法可以将它解析成整数?
当我试图使用Integer.parseInt()
解析265,858时,出现了NumberFormatException
错误。
有没有什么方法可以将它解析成整数?
这个逗号是十进制分隔符还是两个数字?如果是前者,则必须向使用逗号作为十进制分隔符的NumberFormat
类提供Locale
:
NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")
这将得到 265.858
。但是使用美国本地化格式,你将得到 265858
:
NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858")
这是因为在法国中,逗号被视为小数分隔符,而在美国则被视为千位分隔符。
如果这是两个数字,请使用String.split()
将它们拆分成两个单独的字符串,并独立解析每个字符串。
在将其解析为整数之前,您可以删除,
:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
replaceAll
被使用时,对于任何大于 999,999
的数字都是至关重要的。这也消除了从其他答案中抛出/捕获已检查异常的需要。 - Graham RussellNumberFormat
可以将其返回给您。在使用getNumberInstance
方法时,请确保使用正确的Locale。intValue
方法返回一个整数。但是,为了解析异常,您需要将整个内容包装在try/catch块中。try {
NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
//Handle exception
}
一种选择是去掉逗号:
"265,858".replaceAll(",","");
replace
替代 replaceAll
。 - Marko TopolnikString number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
您可以使用NumberFormat.parse
,将其设置为仅整数。
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String)
试试这个:
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)));
265858
或者 265.858
。 - Cratylus