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

标签 javascript validation numeric

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

最佳答案

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)
}

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

仅当字符串 only 包含数字字符时才有效,否则返回 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.

float

请记住,与 +num 不同,parseInt(顾名思义)会将 float 转换为整数,方法是去掉小数点后的所有内容(如果你想使用 parseInt() 因为 这种行为,you're probably better off using another method instead ):

+'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

关于javascript - 如何检查字符串是否为有效数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/175739/

相关文章:

javascript - 如果选中所有复选框,则启用提交按钮

Python NDB : Property validation in queries?

powershell - 在 Powershell 中执行以数值开头的 $PATH 中的 EXE?

r - 在 R 中,为什么 is.numeric(NaN) 打印 "TRUE"?

javascript - 选中单选按钮时启用 HTML 选择,反之亦然

javascript - 由表达式文字生成的正则表达式是否共享单个实例?

javascript - jQuery 验证自定义方法不起作用

javascript - 正则表达式 - javascript 替换所有非数字

javascript - k6中不同群体的不同选择

c# - 在数值中设置点而不是逗号