NumberFormatException
当我尝试解析 265,858 时,我得到了Integer.parseInt()
.
有没有办法把它解析成整数?
NumberFormatException
当我尝试解析 265,858 时,我得到了Integer.parseInt()
.
有没有办法把它解析成整数?
这个逗号是小数分隔符还是这两个数字?在第一种情况下,您必须向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
方法时使用正确的语言环境。
例如,某些语言环境将逗号和小数点交换为您可能习惯的。
然后只需使用该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(",","");
假设这是一个数字,首先点击我的是......
String 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)));