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

javascript validation numbers

1426640 观看

30回复

75191 作者的声誉

在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
作者: Michael Haren 的来源 发布者: 2008 年 8 月 20 日

回应 (30)


59

75191 作者的声誉

这种方式似乎运作良好:

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
作者: Michael Haren 发布者: 20.08.2008 02:22

3

3050 作者的声誉

A couple of tests to add:

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

I came up with this:

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

The solution covers:

  • An optional negative sign at the beginning
  • A single zero, or one or more digits not starting with 0, or nothing so long as a period follows
  • A period that is followed by 1 or more numbers
作者: pottedmeat 发布者: 20.08.2008 02:53

3

42587 作者的声誉

I'd like to add the following:

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

Positive hex numbers start with 0x and negative hex numbers start with -0x. Positive oct numbers start with 0 and negative oct numbers start with -0. This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2 is not valid).

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));
}
作者: Marius 发布者: 20.08.2008 03:40

14

2177 作者的声誉

使用该功能isNaN。我相信如果你测试!isNaN(yourstringhere)它适用于任何这些情况。

作者: bubbassauro 发布者: 21.08.2008 01:02

31

25464 作者的声誉

是的,内置isNaN(object)将比任何正则表达式解析快得多,因为它是内置和编译的,而不是动态解释。

虽然结果与您正在寻找的结果略有不同(尝试一下):

                                              // IS NUMERIC
document.write(!isNaN('-1') + "<br />");      // true
document.write(!isNaN('-1.5') + "<br />");    // true
document.write(!isNaN('0') + "<br />");       // true
document.write(!isNaN('0.42') + "<br />");    // true
document.write(!isNaN('.42') + "<br />");     // true
document.write(!isNaN('99,999') + "<br />");  // false
document.write(!isNaN('0x89f') + "<br />");   // true
document.write(!isNaN('#abcdef') + "<br />"); // false
document.write(!isNaN('1.2.3') + "<br />");   // false
document.write(!isNaN('') + "<br />");        // true
document.write(!isNaN('blah') + "<br />");    // false
作者: travis 发布者: 21.08.2008 04:05

10

4134 作者的声誉

它可以在没有RegExp的情况下完成

function IsNumeric(data){
    return parseFloat(data)==data;
}
作者: Aquatic 发布者: 22.08.2008 03:08

318

306992 作者的声誉

Arrrgh!不要听正则表达式的答案。RegEx对此很苛刻,我不只是说性能。用你的正则表达式来制作微妙的,不可能发现错误是如此容易。

如果你不能使用isNaN(),这应该更好:

function IsNumeric(input)
{
    return (input - 0) == input && (''+input).trim().length > 0;
}

以下是它的工作原理:

(input - 0)表达式强制JavaScript对您的输入值进行类型强制; 必须首先将其解释为减法运算的数字。如果转换为数字失败,则表达式将导致NaN。然后将此数字结果与您传入的原始值进行比较。由于左侧现在是数字,因此再次使用类型强制。既然来自双方的输入都是从相同的原始值强制转换为相同的类型,那么您会认为它们应该始终相同(始终为真)。但是,有一个特殊规则说NaN永远不会等于NaN,因此无法转换为数字的值(并且只有无法转换为数字的值)将导致错误。

检查长度是针对涉及空字符串的特殊情况。另请注意,它会降低到您的0x89f测试,但这是因为在许多环境中,定义数字文字是一种可行的方法。如果要捕获该特定方案,可以添加其他检查。更好的是,如果这是你不使用的原因,isNaN()那么只需将自己的功能包裹起来isNaN(),也可以进行额外的检查。

总之,如果您想知道某个值是否可以转换为数字,实际上会尝试将其转换为数字。


我回去做了一些研究,为什么空白字符串没有预期的输出,我想我现在得到它:一个空字符串被强制0而不是NaN。在长度检查之前简单地修剪字符串将处理这种情况。

运行单元测试新代码,它只在无限和布尔文字上失败,唯一应该是问题的时候是你生成代码(真的,谁会输入文字并检查它是否是数字?你应该知道),这将是一些奇怪的代码生成。

但是,再一次,使用它的唯一原因是,如果由于某种原因你必须避免使用isNaN()。

作者: Joel Coehoorn 发布者: 06.10.2008 04:04

47

1254 作者的声誉

雅虎 UI使用此:

isNumber: function(o) {
    return typeof o === 'number' && isFinite(o);
}
作者: camomileCase 发布者: 14.08.2009 09:07

45

0 作者的声誉

function IsNumeric(num) {
     return (num >=0 || num < 0);
}

这适用于0x23类型数字。

作者: user189277 发布者: 13.10.2009 05:05

2803

590388 作者的声誉

决定

@ Joel的答案非常接近,但在以下情况下会失败:

// Whitespace strings:
IsNumeric(' ')    == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;

// Number literals:
IsNumeric(-1)  == false;
IsNumeric(0)   == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;

前段时间我不得不实现一个IsNumeric函数,找出一个变量是否包含一个数值,不管它的类型如何,它可能是一个String包含数值(我还要考虑指数表示法等),一个Number对象,几乎任何东西都可以传递给那个函数,我不能做任何类型的假设,照顾类型强制(例如,+true == 1;true不应该被认为是"numeric")。

我认为值得分享这套针对众多功能实现的+30单元测试,并且还共享通过我所有测试的那个:

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

由于强制转换为数字,PS isNaNisFinite具有令人困惑的行为。在ES6中,Number.isNaNNumber.isFinite将解决这些问题。使用它们时请记住这一点。


更新这是jQuery现在如何做到的(2.2稳定)

isNumeric: function(obj) {
    var realStringObj = obj && obj.toString();
    return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}

更新Angular 4.3

export function isNumeric(value: any): boolean {
    return !isNaN(value - parseFloat(value));
}
作者: CMS 发布者: 02.12.2009 05:36

4

49 作者的声誉

To me, this is the best way:

isNumber : function(v){
   return typeof v === 'number' && isFinite(v);
}
作者: InsertNameHere 发布者: 28.05.2010 11:30

3

21 作者的声誉

This should work. Some of the functions provided here are flawed, also should be faster than any other function here.

        function isNumeric(n)
        {
            var n2 = n;
            n = parseFloat(n);
            return (n!='NaN' && n2==n);
        }

Explained:

Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number.

It works with numeric strings as well as plain numbers. Does not work with hexadecimal numbers.

Warning: use at your own risk, no guarantees.

作者: user532188 发布者: 06.12.2010 11:30

5

31 作者的声誉

return (input - 0) == input && input.length > 0;

didn't work for me. When I put in an alert and tested, input.length was undefined. I think there is no property to check integer length. So what I did was

var temp = '' + input;
return (input - 0) == input && temp.length > 0;

It worked fine.

作者: jayakumar 发布者: 28.01.2011 11:22

3

21 作者的声誉

My solution,

function isNumeric(input) {
    var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
    var regex = RegExp(number);
    return regex.test(input) && input.length>0;
}

It appears to work in every situation, but I might be wrong.

作者: Manusoftar 发布者: 11.02.2011 11:48

4

41 作者的声誉

An integer value can be verified by:

function isNumeric(value) {
    var bool = isNaN(+value));
    bool = bool || (value.indexOf('.') != -1);
    bool = bool || (value.indexOf(",") != -1);
    return !bool;
};

This way is easier and faster! All tests are checked!

作者: solidarius 发布者: 10.06.2011 12:27

5

31 作者的声誉

If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (Infinity, NaN) and the sign operators +/- (because they are not actually part of the number as far as I concerned, they are separate operators):

I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.

/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d)) 
(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i

Valid numbers would include:

 - 0
 - 00
 - 01
 - 10
 - 0e1
 - 0e01
 - .0
 - 0.
 - .0e1
 - 0.e1
 - 0.e00
 - 0xf
 - 0Xf

Invalid numbers would be

 - 00e1
 - 01e1
 - 00.0
 - 00x0
 - .
 - .e0
作者: Hans Schmucker 发布者: 12.06.2012 08:09

2

640 作者的声誉

I'm using simpler solution:

function isNumber(num) {
    return parseFloat(num).toString() == num
}
作者: Ali Gonabadi 发布者: 16.06.2012 12:25

14

12241 作者的声誉

从jQuery 1.7开始,你可以使用jQuery.isNumeric()

$.isNumeric('-1');      // true
$.isNumeric('-1.5');    // true
$.isNumeric('0');       // true
$.isNumeric('0.42');    // true
$.isNumeric('.42');     // true
$.isNumeric('0x89f');   // true (valid hexa number)
$.isNumeric('99,999');  // false
$.isNumeric('#abcdef'); // false
$.isNumeric('1.2.3');   // false
$.isNumeric('');        // false
$.isNumeric('blah');    // false

请注意,与您所说的不同,0x89f是有效数字(hexa)

作者: Kuf 发布者: 18.02.2013 09:01

38

16080 作者的声誉

接受的答案没有通过你的测试#7,我想这是因为你改变了主意。所以这是对已接受答案的回应,我遇到了问题。

在某些项目中,我需要验证一些数据并尽可能确定它是一个可以在数学运算中使用的javascript数值。

jQuery和其他一些javascript库已经包含了这样一个函数,通常称为isNumericstackoverflow上还有一篇文章已被广泛接受作为答案,与上述库所使用的相同的一般例程。

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

首先,如果参数是长度为1的数组,则上面的代码将返回true,并且该单个元素是上述逻辑认为是数字的类型。在我看来,如果它是一个数组,那么它不是数字。

为了缓解这个问题,我添加了一个检查来从逻辑中对数组进行折扣

function isNumber(n) {
  return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n);
}

当然,您也可以使用Array.isArray,jquery $.isArray或原型Object.isArray而不是Object.prototype.toString.call(n) !== '[object Array]'

我的第二个问题是负十六进制整数文字字符串(“-0xA” - > -10)没有被计为数字。但是,正十六进制整数文字字符串(“0xA” - > 10)被视为数字。我需要两个都是有效的数字。

然后我修改了逻辑以考虑到这一点。

function isNumber(n) {
  return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
}

如果你每次调用函数时都担心正则表达式的创建,那么你可以在一个闭包中重写它,就像这样

var isNumber = (function () {
  var rx = /^-/;

  return function (n) {
      return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(rx, ''));
  };
}());

然后,我接受了CMSs +30测试用例,在jsfiddle上克隆了测试,添加了我的额外测试用例和我上面提到的解决方案。

它可能无法取代广泛接受/使用过的答案,但如果这更像是您所期望的isNumeric函数的结果,那么希望这会有所帮助。

编辑:正如Bergi所指出的,还有其他可能被视为数字的对象,白名单比黑名单更好。考虑到这一点,我会添加标准。

我希望我的isNumeric函数只考虑数字或字符串

考虑到这一点,最好使用它

function isNumber(n) {
  return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
}

测试解决方案

var testHelper = function() {

  var testSuite = function() {
    test("Integer Literals", function() {
      ok(isNumber("-10"), "Negative integer string");
      ok(isNumber("0"), "Zero string");
      ok(isNumber("5"), "Positive integer string");
      ok(isNumber(-16), "Negative integer number");
      ok(isNumber(0), "Zero integer number");
      ok(isNumber(32), "Positive integer number");
      ok(isNumber("040"), "Octal integer literal string");
      ok(isNumber(0144), "Octal integer literal");
      ok(isNumber("-040"), "Negative Octal integer literal string");
      ok(isNumber(-0144), "Negative Octal integer literal");
      ok(isNumber("0xFF"), "Hexadecimal integer literal string");
      ok(isNumber(0xFFF), "Hexadecimal integer literal");
      ok(isNumber("-0xFF"), "Negative Hexadecimal integer literal string");
      ok(isNumber(-0xFFF), "Negative Hexadecimal integer literal");
    });

    test("Foating-Point Literals", function() {
      ok(isNumber("-1.6"), "Negative floating point string");
      ok(isNumber("4.536"), "Positive floating point string");
      ok(isNumber(-2.6), "Negative floating point number");
      ok(isNumber(3.1415), "Positive floating point number");
      ok(isNumber(8e5), "Exponential notation");
      ok(isNumber("123e-2"), "Exponential notation string");
    });

    test("Non-Numeric values", function() {
      equals(isNumber(""), false, "Empty string");
      equals(isNumber("        "), false, "Whitespace characters string");
      equals(isNumber("\t\t"), false, "Tab characters string");
      equals(isNumber("abcdefghijklm1234567890"), false, "Alphanumeric character string");
      equals(isNumber("xabcdefx"), false, "Non-numeric character string");
      equals(isNumber(true), false, "Boolean true literal");
      equals(isNumber(false), false, "Boolean false literal");
      equals(isNumber("bcfed5.2"), false, "Number with preceding non-numeric characters");
      equals(isNumber("7.2acdgs"), false, "Number with trailling non-numeric characters");
      equals(isNumber(undefined), false, "Undefined value");
      equals(isNumber(null), false, "Null value");
      equals(isNumber(NaN), false, "NaN value");
      equals(isNumber(Infinity), false, "Infinity primitive");
      equals(isNumber(Number.POSITIVE_INFINITY), false, "Positive Infinity");
      equals(isNumber(Number.NEGATIVE_INFINITY), false, "Negative Infinity");
      equals(isNumber(new Date(2009, 1, 1)), false, "Date object");
      equals(isNumber(new Object()), false, "Empty object");
      equals(isNumber(function() {}), false, "Instance of a function");
      equals(isNumber([]), false, "Empty Array");
      equals(isNumber(["-10"]), false, "Array Negative integer string");
      equals(isNumber(["0"]), false, "Array Zero string");
      equals(isNumber(["5"]), false, "Array Positive integer string");
      equals(isNumber([-16]), false, "Array Negative integer number");
      equals(isNumber([0]), false, "Array Zero integer number");
      equals(isNumber([32]), false, "Array Positive integer number");
      equals(isNumber(["040"]), false, "Array Octal integer literal string");
      equals(isNumber([0144]), false, "Array Octal integer literal");
      equals(isNumber(["-040"]), false, "Array Negative Octal integer literal string");
      equals(isNumber([-0144]), false, "Array Negative Octal integer literal");
      equals(isNumber(["0xFF"]), false, "Array Hexadecimal integer literal string");
      equals(isNumber([0xFFF]), false, "Array Hexadecimal integer literal");
      equals(isNumber(["-0xFF"]), false, "Array Negative Hexadecimal integer literal string");
      equals(isNumber([-0xFFF]), false, "Array Negative Hexadecimal integer literal");
      equals(isNumber([1, 2]), false, "Array with more than 1 Positive interger number");
      equals(isNumber([-1, -2]), false, "Array with more than 1 Negative interger number");
    });
  }

  var functionsToTest = [

    function(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    },

    function(n) {
      return !isNaN(n) && !isNaN(parseFloat(n));
    },

    function(n) {
      return !isNaN((n));
    },

    function(n) {
      return !isNaN(parseFloat(n));
    },

    function(n) {
      return typeof(n) != "boolean" && !isNaN(n);
    },

    function(n) {
      return parseFloat(n) === Number(n);
    },

    function(n) {
      return parseInt(n) === Number(n);
    },

    function(n) {
      return !isNaN(Number(String(n)));
    },

    function(n) {
      return !isNaN(+('' + n));
    },

    function(n) {
      return (+n) == n;
    },

    function(n) {
      return n && /^-?\d+(\.\d+)?$/.test(n + '');
    },

    function(n) {
      return isFinite(Number(String(n)));
    },

    function(n) {
      return isFinite(String(n));
    },

    function(n) {
      return !isNaN(n) && !isNaN(parseFloat(n)) && isFinite(n);
    },

    function(n) {
      return parseFloat(n) == n;
    },

    function(n) {
      return (n - 0) == n && n.length > 0;
    },

    function(n) {
      return typeof n === 'number' && isFinite(n);
    },

    function(n) {
      return !Array.isArray(n) && !isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
    }

  ];


  // Examines the functionsToTest array, extracts the return statement of each function
  // and fills the toTest select element.
  var fillToTestSelect = function() {
    for (var i = 0; i < functionsToTest.length; i++) {
      var f = functionsToTest[i].toString();
      var option = /[\s\S]*return ([\s\S]*);/.exec(f)[1];
      $("#toTest").append('<option value="' + i + '">' + (i + 1) + '. ' + option + '</option>');
    }
  }

  var performTest = function(functionNumber) {
    reset(); // Reset previous test
    $("#tests").html(""); //Clean test results
    isNumber = functionsToTest[functionNumber]; // Override the isNumber global function with the one to test
    testSuite(); // Run the test

    // Get test results
    var totalFail = 0;
    var totalPass = 0;
    $("b.fail").each(function() {
      totalFail += Number($(this).html());
    });
    $("b.pass").each(function() {
      totalPass += Number($(this).html());
    });
    $("#testresult").html(totalFail + " of " + (totalFail + totalPass) + " test failed.");

    $("#banner").attr("class", "").addClass(totalFail > 0 ? "fail" : "pass");
  }

  return {
    performTest: performTest,
    fillToTestSelect: fillToTestSelect,
    testSuite: testSuite
  };
}();


$(document).ready(function() {
  testHelper.fillToTestSelect();
  testHelper.performTest(0);

  $("#toTest").change(function() {
    testHelper.performTest($(this).children(":selected").val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://rawgit.com/Xotic750/testrunner-old/master/testrunner.js" type="text/javascript"></script>
<link href="https://rawgit.com/Xotic750/testrunner-old/master/testrunner.css" rel="stylesheet" type="text/css">
<h1>isNumber Test Cases</h1>

<h2 id="banner" class="pass"></h2>

<h2 id="userAgent">Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11</h2>

<div id="currentFunction"></div>

<div id="selectFunction">
  <label for="toTest" style="font-weight:bold; font-size:Large;">Select function to test:</label>
  <select id="toTest" name="toTest">
  </select>
</div>

<div id="testCode"></div>

<ol id="tests">
  <li class="pass">
    <strong>Integer Literals <b style="color:black;">(0, 10, 10)</b></strong>

    <ol style="display: none;">
      <li class="pass">Negative integer string</li>

      <li class="pass">Zero string</li>

      <li class="pass">Positive integer string</li>

      <li class="pass">Negative integer number</li>

      <li class="pass">Zero integer number</li>

      <li class="pass">Positive integer number</li>

      <li class="pass">Octal integer literal string</li>

      <li class="pass">Octal integer literal</li>

      <li class="pass">Hexadecimal integer literal string</li>

      <li class="pass">Hexadecimal integer literal</li>
    </ol>
  </li>

  <li class="pass">
    <strong>Foating-Point Literals <b style="color:black;">(0, 6, 6)</b></strong>

    <ol style="display: none;">
      <li class="pass">Negative floating point string</li>

      <li class="pass">Positive floating point string</li>

      <li class="pass">Negative floating point number</li>

      <li class="pass">Positive floating point number</li>

      <li class="pass">Exponential notation</li>

      <li class="pass">Exponential notation string</li>
    </ol>
  </li>

  <li class="pass">
    <strong>Non-Numeric values <b style="color:black;">(0, 18, 18)</b></strong>

    <ol style="display: none;">
      <li class="pass">Empty string: false</li>

      <li class="pass">Whitespace characters string: false</li>

      <li class="pass">Tab characters string: false</li>

      <li class="pass">Alphanumeric character string: false</li>

      <li class="pass">Non-numeric character string: false</li>

      <li class="pass">Boolean true literal: false</li>

      <li class="pass">Boolean false literal: false</li>

      <li class="pass">Number with preceding non-numeric characters: false</li>

      <li class="pass">Number with trailling non-numeric characters: false</li>

      <li class="pass">Undefined value: false</li>

      <li class="pass">Null value: false</li>

      <li class="pass">NaN value: false</li>

      <li class="pass">Infinity primitive: false</li>

      <li class="pass">Positive Infinity: false</li>

      <li class="pass">Negative Infinity: false</li>

      <li class="pass">Date object: false</li>

      <li class="pass">Empty object: false</li>

      <li class="pass">Instance of a function: false</li>
    </ol>
  </li>
</ol>

<div id="main">
  This page contains tests for a set of isNumber functions. To see them, take a look at the source.
</div>

<div>
  <p class="result">Tests completed in 0 milliseconds.
    <br>0 tests of 0 failed.</p>
</div>

作者: Xotic750 发布者: 23.02.2013 06:25

1

1354 作者的声誉

knockoutJs Inbuild库验证函数

通过扩展它,字段得到验证

1)号码

self.number = ko.observable(numberValue).extend({number:true}) ;

测试用例

numberValue = '0.0'    --> true
numberValue = '0'      --> true
numberValue = '25'     --> true
numberValue = '-1'     --> true
numberValue = '-3.5'   --> true
numberValue = '11.112' --> true
numberValue = '0x89f'  --> false
numberValue = ''       --> false
numberValue = 'sfsd'   --> false
numberValue = 'dg##$'  --> false

2)数字

self.number = ko.observable(numberValue).extend({digit:true}) ;

测试用例

numberValue = '0'      --> true
numberValue = '25'     --> true
numberValue = '0.0'    --> false
numberValue = '-1'     --> false
numberValue = '-3.5'   --> false
numberValue = '11.112' --> false
numberValue = '0x89f'  --> false
numberValue = ''       --> false
numberValue = 'sfsd'   --> false
numberValue = 'dg##$'  --> false

3)最小和最大

self.number = ko.observable(numberValue).extend({min:5})。extend({max:10}) ;

此字段仅接受5到10之间的值

测试用例

numberValue = '5'    --> true
numberValue = '6'    --> true
numberValue = '6.5'  --> true
numberValue = '9'    --> true
numberValue = '11'   --> false
numberValue = '0'    --> false
numberValue = ''    --> false
作者: nav0611 发布者: 27.02.2013 03:38

1

2484 作者的声誉

@CMS'回答:你的代码片段在我的机器上使用nodejs的空白案例失败了。所以我把它与@ joel的答案结合起来 :

is_float = function(v) {
    return !isNaN(v) && isFinite(v) &&
        (typeof(v) == 'number' || v.replace(/^\s+|\s+$/g, '').length > 0);
}

我将它与那些浮动的案例进行了单独测试:

var t = [
        0,
        1.2123,
        '0',
        '2123.4',
        -1,
        '-1',
        -123.423,
        '-123.432',
        07,
        0xad,
        '07',
        '0xad'
    ];

和那些没有浮点数的情况(包括空白空间和对象/数组):

    var t = [
        'hallo',
        [],
        {},
        'jklsd0',
        '',
        "\t",
        "\n",
        ' '
    ];

一切都按预期在这里工作。也许这有帮助。

完整的源代码可以在这里找到。

作者: Phil 发布者: 14.04.2013 10:14

4

2801 作者的声誉

Here's a lil bit improved version (probably the fastest way out there) that I use instead of exact jQuery's variant, I really don't know why don't they use this one:

function isNumeric(val) {
    return !isNaN(+val) && isFinite(val);
}

The downside of jQuery's version is that if you pass a string with leading numerics and trailing letters like "123abc" the parseFloat | parseInt will extract the numeric fraction out and return 123, BUT, the second guard isFinite will fail it anyway. With the unary + operator it will die on the very first guard since + throws NaN for such hybrids :) A little performance yet I think a solid semantic gain.

作者: Arman McHitarian 发布者: 20.05.2013 04:48

4

10248 作者的声誉

Only problem I had with @CMS's answer is the exclusion of NaN and Infinity, which are useful numbers for many situations. One way to check for NaN's is to check for numeric values that don't equal themselves, NaN != NaN! So there are really 3 tests you'd like to deal with ...

function isNumber(n) {
  n = parseFloat(n);
  return !isNaN(n) || n != n;
}
function isFiniteNumber(n) {
  n = parseFloat(n);
  return !isNaN(n) && isFinite(n);
}    
function isComparableNumber(n) {
  n = parseFloat(n);
  return (n >=0 || n < 0);
}

isFiniteNumber('NaN')
false
isFiniteNumber('OxFF')
true
isNumber('NaN')
true
isNumber(1/0-1/0)
true
isComparableNumber('NaN')
false
isComparableNumber('Infinity')
true

My isComparableNumber is pretty close to another elegant answer, but handles hex and other string representations of numbers.

作者: hobs 发布者: 06.06.2013 11:39

1

127 作者的声誉

以下似乎适用于许多情况:

function isNumeric(num) {
    return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);
}

这是建立在这个答案的基础上(也是这个答案):https//stackoverflow.com/a/1561597/1985601

作者: daniel1426 发布者: 20.12.2013 10:01

5

2976 作者的声誉

我意识到原始问题没有提到jQuery,但如果你使用jQuery,你可以这样做:

$.isNumeric(val)

简单。

https://api.jquery.com/jQuery.isNumeric/ (从jQuery 1.7开始)

作者: Sean the Bean 发布者: 13.01.2014 04:42

1

1863 作者的声誉

我意识到这已被多次回答,但以下是一个不错的候选人,在某些情况下可能会有用。

应该注意的是,假设'.42'不是数字,'4' 不是数字,所以应该考虑到这一点。

function isDecimal(x) {
  return '' + x === '' + +x;
}

function isInteger(x) {
  return '' + x === '' + parseInt(x);
}

isDecimal通过下面的测试:

function testIsNumber(f) {
  return f('-1') && f('-1.5') && f('0') && f('0.42')
    && !f('.42') && !f('99,999') && !f('0x89f')
    && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');
}

这里的想法是每个数字或整数都有一个“规范”字符串表示,并且每个非规范表示都应该被拒绝。所以我们转换为数字并返回,并查看结果是否是原始字符串。

这些功能是否对您有用取决于用例。一个特征是不同的字符串代表不同的数字(如果两者都通过isNumber()测试)。

这与数字作为对象属性名称相关。

var obj = {};
obj['4'] = 'canonical 4';
obj['04'] = 'alias of 4';
obj[4];  // prints 'canonical 4' to the console.
作者: donquixote 发布者: 13.04.2014 11:28

2

5512 作者的声誉

None of the answers return false for empty strings, a fix for that...

function is_numeric(n)
{
 return (n != '' && !isNaN(parseFloat(n)) && isFinite(n));
}
作者: John 发布者: 23.12.2014 02:38

2

5908 作者的声誉

To check if a variable contains a valid number and not just a String which looks like a number, Number.isFinite(value) can be used.

This is part of the language since ES2015

Examples:

Number.isFinite(Infinity)   // false
Number.isFinite(NaN)        // false
Number.isFinite(-Infinity)  // false

Number.isFinite(0)          // true
Number.isFinite(2e64)       // true

Number.isFinite('0')        // false
Number.isFinite(null)       // false
作者: adius 发布者: 10.04.2016 05:53

1

384 作者的声誉

function inNumeric(n){
   return Number(n).toString() === n;
}

如果n为numeric,Number(n)则返回数值toString()并将其转回字符串。但如果n不是数字Number(n)将返回,NaN因此它将与原始不匹配n

作者: chrmcpn 发布者: 10.08.2016 08:17

1

2325 作者的声誉

您可以通过很多方式最小化此功能,也可以使用自定义正则表达式为负值或自定义图表实现它:

$('.number').on('input',function(){
    var n=$(this).val().replace(/ /g,'').replace(/\D/g,'');
    if (!$.isNumeric(n))
        $(this).val(n.slice(0, -1))
    else
        $(this).val(n)
});
作者: Vixed 发布者: 23.02.2017 02:56
32x32