188

除了Integer.parseInt()处理减号(如记录)外,和之间还有其他区别Integer.valueOf()Integer.parseInt()

而且由于两者都不能解析,十进制千位分隔符(产生NumberFormatException),是否有可用的 Java 方法来做到这一点?

4

5 回答 5

244

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));
于 2011-09-08T22:00:53.047 回答
30

First Question: Difference between parseInt and valueOf in java?

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
于 2011-09-08T22:00:38.050 回答
21

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

于 2011-09-08T22:02:29.600 回答
9

这两种方法的区别在于:

  • parseXxx()返回原始类型
  • valueOf()返回该类型的包装对象引用。
于 2016-09-09T13:36:51.647 回答
8

parseInt() parses String to int while valueOf() additionally wraps this int into Integer. That's the only difference.

If you want to have full control over parsing integers, check out NumberFormat with various locales.

于 2011-09-08T22:01:24.340 回答