如何检查 Value 是否为 JavaScript 中的浮点数
JavaScript 中检查一个值是否为浮点数:
- 检查该值是否具有数字类型并且不是整数。
-
检查该值是否不是
NaN
。 -
如果一个值是一个数字,不是
NaN
也不是整数,那么它就是一个浮点数。
function isFloat(value) {
if (
typeof value === 'number' &&
!Number.isNaN(value) &&
!Number.isInteger(value)
) {
return true;
}
return false;
}
console.log(isFloat(1)); // 👉️ false
console.log(isFloat(1.5)); // 👉️ true
console.log(isFloat(-1.5)); // 👉️ true
console.log(isFloat('1.5')); // 👉️ false
我们首先检查提供的值是否具有数字类型。 如果不是,我们会立即返回 false。
我们使用逻辑与 &&
运算符来检查多个条件。 要运行我们的 if 块,必须满足所有条件。
第二个条件检查提供的值不是 NaN(不是数字)。 不幸的是,NaN 在 JavaScript 中有一种数字类型。
console.log(typeof Number.NaN); // 👉️ number
我们必须进行
NaN
检查,因为NaN
具有数字类型,而不是整数。
如果提供的值是数字类型,不是 NaN 也不是整数,我们返回 true。
使用 Number.isInteger 方法时有一个问题。
如果传入值,则返回 true:
- 是一个整数
- 是一个可以表示为整数的浮点数
下面是一个可以表示为整数的浮点数示例。
console.log(Number.isInteger(10.0)); // 👉️ true
将 10.0 视为整数还是浮点数取决于您的用例。
我们对该函数的实现将 1.0 和 5.0 之类的数字视为非浮点数。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。