如何在 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

更新於: 03-Oct-2020

954 檢視

開啟你的職業生涯

完成課程,獲得證書

開始
廣告
© . All rights reserved.