如何检查数字是浮点数还是整数 - JavaScript?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/6 2:52:17

假设我们有以下变量 −

var value1 = 10;
var value2 = 10.15;

使用 Number() 条件检查数字是浮点数还是整数 −

Number(value) === value && value % 1 !== 0;
}

示例

以下是代码 −

function checkNumberIfFloat(value) {
   return Number(value) === value && value % 1 !== 0;
}
var value1 = 10;
var value2 = 10.15;
if (checkNumberIfFloat(value1) == true)
   console.log("The value is float=" + value1);
else
   console.log("The value is not float=" + value1);
if (checkNumberIfFloat(value2) == true)
   console.log("The value is float=" + value2);
else
   console.log("The value is not float=" + value2);

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo218.js。

输出

输出如下 −

PS C:\Users\Amit\JavaScript-code> node demo218.js
The value is not float=10
The value is float=10.15

相关文章


有用资源