确定String是否为数字并使用Java进行转换? [英] Determine if a String is a number and convert in Java?
问题描述
我知道之前经常会问过这个问题的变体(参见此处和此处例如),但不 完全重复。
I know variants of this question have been asked frequently before (see here and here for instance), but this is not an exact duplicate of those.
我想检查是否字符串
是一个数字,如果是这样,我想将它存储为 double
。有几种方法可以做到这一点,但所有这些方法似乎都不适合我的目的。
I would like to check if a String
is a number, and if so I would like to store it as a double
. There are several ways to do this, but all of them seem inappropriate for my purposes.
一种解决方案是使用 Double.parseDouble(s )
或类似的新的BigDecimal
。但是,如果存在逗号,则这些解决方案不起作用(因此1,234会导致异常)。我当然可以在使用这些技术之前删除所有逗号,但这似乎会在其他语言环境中造成大量问题。
One solution would be to use Double.parseDouble(s)
or similarly new BigDecimal(s)
. However, those solutions don't work if there are commas present (so "1,234" would cause an exception). I could of course strip out all commas before using these techniques, but that would seem to pose loads of problems in other locales.
我查看了Apache Commons NumberUtils.isNumber(s)
,但遭受相同的逗号问题。
I looked at Apache Commons NumberUtils.isNumber(s)
, but that suffers from the same comma issue.
我考虑过 NumberFormat
或 DecimalFormat
,但这些似乎太宽松了。例如,1A被格式化为1而不是表示它不是数字。此外,像127.0.0.1这样的东西将被算作数字127而不是表明它不是数字。
I considered NumberFormat
or DecimalFormat
, but those seemed far too lenient. For instance, "1A" is formatted to "1" instead of indicating that it's not a number. Furthermore, something like "127.0.0.1" will be counted as the number 127 instead of indicating that it's not a number.
我觉得我的要求不是那么异国情调我是第一个这样做的人,但没有一个解决方案完全符合我的需要。我想即使我不知道完全我需要什么(否则我可以编写自己的解析器),但我知道上述解决方案因指示的原因不起作用。是否存在任何解决方案,或者我是否需要准确弄清楚我需要什么并为其编写自己的代码?
I feel like my requirements aren't so exotic that I'm the first to do this, but none of the solutions does exactly what I need. I suppose even I don't know exactly what I need (otherwise I could write my own parser), but I know the above solutions do not work for the reasons indicated. Does any solution exist, or do I need to figure out precisely what I need and write my own code for it?
推荐答案
声音很奇怪,但我会尝试按照这个答案并使用 java.util.Scanner
。
Sounds quite weird, but I would try to follow this answer and use java.util.Scanner
.
Scanner scanner = new Scanner(input);
if (scanner.hasNextInt())
System.out.println(scanner.nextInt());
else if (scanner.hasNextDouble())
System.out.println(scanner.nextDouble());
else
System.out.println("Not a number");
对于 1A
等输入, 127.0.0.1
, 1,234
, 6.02e-23
我得到了以下输出:
For inputs such as 1A
, 127.0.0.1
, 1,234
, 6.02e-23
I get the following output:
Not a number
Not a number
1234
6.02E-23
Scanner.useLocale
可用于更改到期望的地区。
Scanner.useLocale
can be used to change to the desired locale.
这篇关于确定String是否为数字并使用Java进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!