如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
这是我的:
function isInt(quale) {
var valore = $('#'+quale).val().toLowerCase();
if (isNaN(Number(String(valore))) || (valore.indexOf("e") > 0)) {
// Not int
} else {
// Is Int!
}
}
还有这个:
function isFloat(quale) {
var valore = $('#'+quale).val();
valore = valore.replace(",", "");
if (isNaN(String(valore)) || (valore.indexOf("e") > 0)) {
// Not Float
} else {
// Float
}
}
Ad majora!
其他回答
function isInt(n)
{
return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
return n != "" && !isNaN(n) && Math.round(n) != n;
}
适用于所有情况。
在这里尝试了一些答案,我最终写出了这个解决方案。这也适用于字符串中的数字。
function isInt(number) {
if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
return !(number - parseInt(number));
}
function isFloat(number) {
if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
return number - parseInt(number) ? true : false;
}
var测试={“integer”:1,“浮动”:1.1,“整数InString”:“5”,“floatInString”:“5.5”,“负Int”:-345,“负浮动”:-34.98,“negativeIntString”:“-45”,“negativeFloatString”:“-23.09”,“notValidFalse”:false,“notValidTrue”:true,“notValidString”:“45lorem”,“notValidStringFloat”:“4.5lorem”,'notValidNan':NaN,“notValidObj”:{},“notValidArr”:[1,2],};函数isInt(数字){如果(!/^[“|']{0,1}[-]{0.1}\d{0,}(\.{0,1}\d+)[“|']{0 1}$/.test(数字))返回false;回来(number-parseInt(number));}函数isFloat(数字){如果(!/^[“|']{0,1}[-]{0.1}\d{0,}(\.{0,1}\d+)[“|']{0 1}$/.test(数字))返回false;返回number-parseInt(number)?真:假;}函数测试函数(obj){var keys=对象.keys(obj);var values=对象.值(obj);values.forEach(函数(元素,索引){console.log(`${keys[index]}(${element})var是整数吗${isInt(元素)}`);console.log(`${keys[index]}(${element})var是浮点数吗${isFloat(元素)}`);});}testFunctions(测试);
这真的取决于你想要实现什么。如果你想“模仿”强类型语言,那么我建议你不要尝试。正如其他人提到的,所有数字都有相同的表示(相同类型)。
使用Claudiu提供的内容:
isInteger(1.0)->true
这看起来很正常,但在C这样的情况下,你会错
var isInt = function (n) { return n === (n | 0); };
还没有这样的案例。
正如其他人提到的,你在JS中只有双打。那么,如何定义一个整数?只需检查舍入数字是否等于自身:
function isInteger(f) {
return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }