如何检查字符串是否为有效数字?

新手上路,请多包涵

我希望在与旧的 VB6 IsNumeric() 函数相同的概念空间中有一些东西?

原文由 Electrons_Ahoy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

2020 年 10 月 2 日: 请注意,许多基本方法都充满了细微的错误(例如空格、隐式部分解析、基数、数组强制等),这里的许多答案都没有考虑到这些错误。以下实现可能对您有用,但请注意,它不支持除小数点“ . ”以外的数字分隔符:

 function isNumeric(str) {
 if (typeof str != "string") return false // we only process strings!
 return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
 !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
 }


要检查变量(包括字符串)是否为数字,请检查它是否不是数字:

无论变量内容是字符串还是数字,这都有效。

 isNaN(num) // returns true if the variable does NOT contain a valid number

例子

isNaN(123) // false
 isNaN('123') // false
 isNaN('1e10000') // false (This translates to Infinity, which is a number)
 isNaN('foo') // true
 isNaN('10px') // true
 isNaN('') // false
 isNaN(' ') // false
 isNaN(false) // false

当然,如果需要,您可以否定这一点。例如,要实现您给出的 IsNumeric 示例:

 function isNumeric(num){
 return !isNaN(num)
 }

要将包含数字的字符串转换为数字:

仅当字符串 包含数字字符时才有效,否则返回 NaN

 +num // returns the numeric value of the string, or NaN
 // if the string isn't purely numeric characters

例子

+'12' // 12
 +'12.' // 12
 +'12..' // NaN
 +'.12' // 0.12
 +'..12' // NaN
 +'foo' // NaN
 +'12px' // NaN

将字符串松散地转换为数字

用于将 ‘12px’ 转换为 12,例如:

 parseInt(num) // extracts a numeric value from the
 // start of the string, or NaN.

例子

parseInt('12') // 12
 parseInt('aaa') // NaN
 parseInt('12px') // 12
 parseInt('foo2') // NaN These last three may
 parseInt('12a5') // 12 be different from what
 parseInt('0x10') // 16 you expected to see.

花车

请记住,与 +num 不同, parseInt (顾名思义)将通过切除小数点后的所有内容将浮点数转换为整数(如果 由于 这种行为而要使用 parseInt()您可能会更好关闭使用另一种方法):

 +'12.345' // 12.345
 parseInt(12.345) // 12
 parseInt('12.345') // 12

空字符串

空字符串可能有点违反直觉。 +num 将空字符串或带空格的字符串转换为零,并且 isNaN() 假设相同:

 +'' // 0
 +' ' // 0
 isNaN('') // false
 isNaN(' ') // false

但是 parseInt() 不同意:

 parseInt('') // NaN
 parseInt(' ') // NaN

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您只是想检查字符串是否为整数(无小数位),正则表达式是一个不错的选择。其他方法,如 isNaN 对于如此简单的事情来说太复杂了。

 function isNumeric(value) {
    return /^-?\d+$/.test(value);
}

console.log(isNumeric('abcd'));         // false
console.log(isNumeric('123a'));         // false
console.log(isNumeric('1'));            // true
console.log(isNumeric('1234567890'));   // true
console.log(isNumeric('-23'));          // true
console.log(isNumeric(1234));           // true
console.log(isNumeric(1234n));          // true
console.log(isNumeric('123.4'));        // false
console.log(isNumeric(''));             // false
console.log(isNumeric(undefined));      // false
console.log(isNumeric(null));           // false

只允许 整数使用这个:

 function isNumeric(value) {
    return /^\d+$/.test(value);
}

console.log(isNumeric('123'));          // true
console.log(isNumeric('-23'));          // false

原文由 Gavin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题