如何在Javascript中检查值是否为整数(特殊情况1.0应该为float) [英] How to check if a value is an integer in Javascript (special case 1.0 should be float)

查看:102
本文介绍了如何在Javascript中检查值是否为整数(特殊情况1.0应该为float)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些类型检查功能.我想要:

I am writing some type check functions. I want:

  • isInteger
  • isFloat

在编写isInteger时,我注意到isInteger(1.0)返回true.我希望它返回false.

While writing isInteger, I noticed that isInteger(1.0) returns true. I want this to return false.

我的功能是这样的:

function isInteger(value) {
    return typeof value === 'number' && value % 1 === 0;
}

我还注意到它对1.0返回true,因为参数'value'立即转换为1(我不想要).

I also noticed that it return true for 1.0 because the argument 'value' is immediately converted to 1 (which I don't want).

我这样做了:

function isInteger(value) {
    console.log(value)          // It prints 1 if value is 1.0
    return typeof value === 'number' && value % 1 === 0;
}

当然,我考虑了可能需要使用regEx的情况:

Of course, I consider the situation where I might need to use regEx:

var regEx = /^-?[0-9]+$/;
regEx.test(value)

但是,首先我需要该函数实际测试值1.0而不是1.

BUT, first I need the function to actually test the value 1.0 instead of 1.

如何在功能参数中维护1.0?

How could I do this in order to maintain the 1.0 in the function argument?

谢谢

推荐答案

如果您键入

var a = 1;
var b = 1.0;

ab的存储方式完全相同.没有没有差异.这是因为JavaScript中只有一种数字存储类型,它是 IEEE754双精度浮点数.

a and b are stored exactly the same way. There's no difference. That's because there's only one storage type for numbers in JavaScript, it's IEEE754 double precision floating point.

如果要使它们保持不同,请不要使用数字格式,例如,可以将它们保留为字符串.

If you want to keep them different, don't use the number format, you may keep them as strings for example.

这篇关于如何在Javascript中检查值是否为整数(特殊情况1.0应该为float)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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