如何在java中将包含逗号的数字字符串解析为整数? [英] How to parse number string containing commas into an integer in java?

查看:46
本文介绍了如何在java中将包含逗号的数字字符串解析为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt().

有没有办法解析成整数?

Is there any way to parse it into an integer?

推荐答案

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

Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:

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

这导致 265.858.但是使用美国语言环境你会得到 265858:

This results in 265.858. But using US locale you'll get 265858:

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

那是因为在法国他们将逗号视为小数点分隔符,而在美国则将逗号视为分组(千位)分隔符.

That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.

如果这是两个数字 - String.split() 它们并独立解析两个单独的字符串.

If these are two numbers - String.split() them and parse two separate strings independently.

这篇关于如何在java中将包含逗号的数字字符串解析为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆