Java中转换带逗号的字符串为整数时遇NumberFormatException怎么办?
问题解决:带千位分隔符的字符串转整数报NumberFormatException
问题重现
尝试将带千位逗号的金额字符串"3,456"转换为整数时,使用Integer.parseInt()或Integer.valueOf()都会抛出NumberFormatException,示例代码如下:
public static void main(String[] args) { String name="3,456"; int value= Integer.parseInt(name); System.out.println(value); }
运行后触发异常的原因是:Java的Integer类解析方法无法识别千位分隔符逗号,仅能解析纯数字组成的字符串。
解决方案
方法1:移除逗号后直接转换
针对确定只有千位逗号干扰的场景,直接移除字符串中的逗号再转换即可:
public static void main(String[] args) { String name = "3,456"; // 移除所有逗号 String cleanedNumber = name.replace(",", ""); int value = Integer.parseInt(cleanedNumber); System.out.println(value); // 输出3456 }
方法2:用NumberFormat适配多地区格式
如果需要兼容不同地区的数字格式(比如部分欧洲地区用点作为千位分隔符),可以使用NumberFormat类解析:
import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public static void main(String[] args) throws ParseException { String name = "3,456"; // 指定美国地区格式,识别千位逗号 NumberFormat numberFormat = NumberFormat.getInstance(Locale.US); Number parsedNumber = numberFormat.parse(name); int value = parsedNumber.intValue(); System.out.println(value); // 输出3456 }
这种方法能自动适配对应地区的数字分隔规则,适用性更广。
内容的提问来源于stack exchange,提问作者srilatha
相关产品推荐
相关产品推荐

