typescript 在打字稿中,如何检查字符串是否为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23437476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Typescript, How to check if a string is Numeric
提问by user3509546
In Typescript, this shows an error saying isNaN accepts only numeric values
在 Typescript 中,这会显示一个错误,指出 isNaN 只接受数值
isNaN('9BX46B6A')
and this returns false because parseFloat('9BX46B6A')
evaluates to 9
这将返回 false 因为parseFloat('9BX46B6A')
评估为9
isNaN(parseFloat('9BX46B6A'))
I can still run with the error showing up in Visual Studio, but I would like to do it the right way.
我仍然可以在 Visual Studio 中显示错误的情况下运行,但我想以正确的方式进行。
Currently, I have written this modified function -
目前,我已经编写了这个修改后的函数 -
static isNaNModified = (inputStr: string) => {
var numericRepr = parseFloat(inputStr);
return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length;
}
回答by C Snover
The way to convert a string to a number is with Number
, not parseFloat
.
将字符串转换为数字的方法是使用Number
,而不是parseFloat
。
Number('1234') // 1234
Number('9BX9') // NaN
You can also use the unary plus operator if you like shorthand:
如果您喜欢速记,也可以使用一元加运算符:
+'1234' // 1234
+'9BX9' // NaN
Be careful when checking against NaN (the operator ===
and !==
don't work as expected with NaN
). Use:
检查 NaN 时要小心(操作符===
和!==
不按预期工作NaN
)。用:
isNaN(maybeNumber) // returns true if NaN, otherwise false
回答by Richard Lee
Update 2
更新 2
This method is no longer available in rxjs v6
此方法在 rxjs v6 中不再可用
I'm solved it by using the isNumericoperator from rxjslibrary (importing rxjs/util/isNumeric
我通过解决它ISNUMERIC运营商从rxjs库(进口rxjs / UTIL / ISNUMERIC
Update
更新
import { isNumeric } from 'rxjs/util/isNumeric';
import { isNumeric } from 'rxjs/util/isNumeric';
. . .
. . .
var val = "5700";
if (isNumeric(val)){
alert("it is number !");
}
回答by Gil Epshtain
function isNumber(value: string | number): boolean
{
return ((value != null) &&
(value !== '') &&
!isNaN(Number(value.toString())));
}
回答by Jan
I would choose an existing and already tested solution. For example this from rxjs in typescript:
我会选择一个现有的并且已经测试过的解决方案。例如,来自打字稿中的 rxjs:
function isNumeric(val: any): val is number | string {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
}
Without rxjs isArray() function and with simplefied typings:
没有 rxjs isArray() 函数和简单的类型:
function isNumeric(val: any): boolean {
return !(val instanceof Array) && (val - parseFloat(val) + 1) >= 0;
}
You should always test such functions with your use cases. If you have special value types, this function may not be your solution. You can test the function here.
您应该始终使用您的用例测试此类功能。如果您有特殊的值类型,此函数可能不是您的解决方案。 您可以在此处测试该功能。
Results are:
结果是:
enum : CardTypes.Debit : true
decimal : 10 : true
hexaDecimal : 0xf10b : true
binary : 0b110100 : true
octal : 0o410 : true
stringNumber : '10' : true
string : 'Hello' : false
undefined : undefined : false
null : null : false
function : () => {} : false
array : [80, 85, 75] : false
turple : ['Kunal', 2018] : false
object : {} : false
As you can see, you have to be careful, if you use this function with enums.
如您所见,如果将此函数与枚举一起使用,则必须小心。
回答by Nick H
Simple answer: (watch for blank & null)
简单的答案:(注意空白和空值)
isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;
isNaN(null) = false;
回答by RTW
Most of the time the value that we want to check is string or number, so here is function that i use:
大多数情况下,我们要检查的值是字符串或数字,所以这是我使用的函数:
const isNumber = (n: string | number): boolean =>
!isNaN(parseFloat(String(n))) && isFinite(Number(n));
const willBeTrue = [0.1, '1', '-1', 1, -1, 0, -0, '0', "-0", 2e2, 1e23, 1.1, -0.1, '0.1', '2e2', '1e23', '-0.1', ' 898', '080']
const willBeFalse = ['9BX46B6A', "+''", '', '-0,1', [], '123a', 'a', 'NaN', 1e10000, undefined, null, NaN, Infinity, () => {}]
回答by Felix
For full numbers (non-floats) in Angular you can use:
对于 Angular 中的完整数字(非浮点数),您可以使用:
if (Number.isInteger(yourVariable)) {
...
}
if (Number.isInteger(yourVariable)) {
...
}
回答by James Paterson
You can use the Number.isFinite()
function:
您可以使用该Number.isFinite()
功能:
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite('0'); // false
Number.isFinite(null); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
Note: there's a significant difference between the global function isFinite()
and the latter Number.isFinite()
. In the case of the former, string coercion is performed - so isFinite('0') === true
whilst Number.isFinite('0') === false
.
注意:全局函数isFinite()
和后者有显着区别Number.isFinite()
。在前者的情况下,执行字符串强制 - 所以isFinite('0') === true
while Number.isFinite('0') === false
。
Also, note that this is not available in IE!
另外,请注意,这在 IE 中不可用!
回答by basarat
Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.
字符串是否可以解析为数字是一个运行时问题。Typescript 不支持此用例,因为它专注于编译时(而非运行时)安全。