适用于Java的最优雅的isNumeric()解决方案 [英] Most elegant isNumeric() solution for java

查看:1686
本文介绍了适用于Java的最优雅的isNumeric()解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在将一小段PHP代码移植到Java,并且我依靠函数is_numeric($x)来确定$x是否为数字. Java中似乎没有等效的函数,并且我对到目前为止找到的当前解决方案不满意.

I'm porting a small snippet of PHP code to java right now, and I was relying on the function is_numeric($x) to determine if $x is a number or not. There doesn't seem to be an equivalent function in java, and I'm not satisfied with the current solutions I've found so far.

我倾向于此处找到的正则表达式解决方案: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric

I'm leaning toward the regular expression solution found here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric

我应该使用哪种方法?为什么?

Which method should I use and why?

推荐答案

请注意,PHP isNumeric()函数将正确地确定十六进制和科学计数法是数字,而您链接到的正则表达式则不会.

Note that the PHP isNumeric() function will correctly determine that hex and scientific notation are numbers, which the regex approach you link to will not.

一种选择(尤其是如果您已经在使用Apache Commons库的话)是使用

One option, especially if you are already using Apache Commons libraries, is to use NumberUtils.isNumber(), from Commons-Lang. It will handle the same cases that the PHP function will handle.

这篇关于适用于Java的最优雅的isNumeric()解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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