kev*_*uku 3 javascript floating-point types integer decimal
我正在使用一个函数来验证作为参数传递的数字是 JavaScript 中的浮点数还是整数。
该方法适用于“4.34”等数字,即具有非零小数的数字,但对于“3.0”等数字则失败,返回整数而不是浮点数。
这是到目前为止我能想到的代码
function dataType(x) {
if (typeof x === 'number' && ){
if (Math.round(x) === x ){
return 'integer';
}
return 'float';
}
}
console.log(dataType(8)); //integer
console.log(dataType(3.01)); //float
console.log(dataType(3.0)); // should return float
Run Code Online (Sandbox Code Playgroud)
我非常感谢有关如何在 JavaScript 中执行此操作的帮助。
提前致谢。
更新:我想console.log(dataType(3.0));返回浮动。
JS 中的每个数字都是浮点数。JS 中只有一种数字类型 ( Number)。
因此,没有跨浏览器的方法来保证以下内容之间的差异:
3
3.0
3.0000000000000
Run Code Online (Sandbox Code Playgroud)
等等。
即使在现代浏览器中,(3.0000).toString( ) === "3"; //true.
尝试在 JS 中强制转换或强制数字类型安全是毫无意义的。
根据需要使用所需的精度处理数字格式的数字,将其转换为字符串或从字符串中转换出来。