如何在 JavaScript 中檢查一個數字是浮點數還是整數?
假設我們有如下變數 −
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP