在JavaScript中验证十进制数字 - IsNumeric()

在JavaScript中验证小数的最干净、最有效的方法是什么?

奖励分。

1.清晰度。解决方案应该是干净和简单的。 2.跨平台。

测试案例。

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

这种方式似乎很有效。

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

并进行测试。

// alert(TestIsNumeric());

function TestIsNumeric(){
    var results = ''
    results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";
    results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";
    results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";
    results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";
    results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";
    results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";
    results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";
    results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";
    results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";
    results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";
    results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";

    return results;
}

我从http://www.codetoad.com/javascript/isnumeric.asp,借用了这个词组。解释一下。

/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string
评论(3)

我想补充如下。

1. IsNumeric('0x89f') => true
2.IsNumeric('075') => true

正的十六进制数字以0x开始,负的十六进制数字以-0x开始。 正的八进制数字以0开始,负的八进制数字以0开始。 这个版本考虑到了大部分已经提到的内容,但包括了十六进制和八进制数字、负科学计数、无限大,并删除了十进制科学计数(4e3.2无效)。

function IsNumeric(input){
  var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
  return (RE.test(input));
}
评论(1)

有几个测试要补充。

IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false

我想出了这个办法。

function IsNumeric(input) {
    return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}

该解决方案涵盖。

  • 开头是一个可选的负号
  • 一个零,或一个或多个不以0开头的数字,或没有任何数字,只要有句号就可以了
  • 一个句号,后面有一个或多个数字
评论(0)