在打字稿中,如何检查字符串是否为数字 [英] In Typescript, How to check if a string is Numeric

查看:24
本文介绍了在打字稿中,如何检查字符串是否为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Typescript 中,这显示了一个错误,指出 isNaN 只接受数值

In Typescript, this shows an error saying isNaN accepts only numeric values

isNaN('9BX46B6A')

这将返回 false 因为 parseFloat('9BX46B6A') 计算结果为 9

and this returns false because parseFloat('9BX46B6A') evaluates to 9

isNaN(parseFloat('9BX46B6A'))

我仍然可以在 Visual Studio 中显示错误的情况下运行,但我想以正确的方式进行.

I can still run with the error showing up in Visual Studio, but I would like to do it the right way.

目前,我已经编写了这个修改过的函数 -

Currently, I have written this modified function -

static isNaNModified = (inputStr: string) => {
    var numericRepr = parseFloat(inputStr);
    return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length;
}

推荐答案

将字符串转换为数字的方式是使用 Number,而不是 parseFloat.

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

如果您喜欢速记,也可以使用一元加号运算符:

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

在检查 NaN 时要小心(运算符 ===!==NaN 不符合预期).使用:

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

这篇关于在打字稿中,如何检查字符串是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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