joa*_*r84 0 javascript regex floating-point integer typechecking
我正在写一些类型检查功能.我想要:
在编写isInteger时,我注意到isInteger(1.0)返回true.我希望这会返回false.
我的功能是这样的:
function isInteger(value) {
return typeof value === 'number' && value % 1 === 0;
}
Run Code Online (Sandbox Code Playgroud)
我还注意到它返回true为1.0,因为参数'value'立即转换为1(我不想要).
我这样做了:
function isInteger(value) {
console.log(value) // It prints 1 if value is 1.0
return typeof value === 'number' && value % 1 === 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,我考虑可能需要使用regEx的情况:
var regEx = /^-?[0-9]+$/;
regEx.test(value)
Run Code Online (Sandbox Code Playgroud)
但是,首先我需要函数来实际测试值1.0而不是1.
我怎么能这样做才能在函数参数中维护1.0?
谢谢
如果你输入
var a = 1;
var b = 1.0;
Run Code Online (Sandbox Code Playgroud)
a并b以完全相同的方式存储.有没有区别.那是因为JavaScript中的数字只有一种存储类型,它是IEEE754双精度浮点数.
如果您想保持它们不同,请不要使用数字格式,例如,您可以将它们保留为字符串.