Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra số float hay integer trong JavaScript

Sử dụng Number(value) === value && value % 1 !== 0 để kiểm tra số thực (float).

Mã thực hiện

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

Kết quả

The value is not float=10
The value is float=10.15