如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何发现一个数字是浮点数或整数?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
当前回答
要检查数字是否为Int并应用2十进制格式,可以在React Native中使用以下公式。
isInt = (n) => {
return n % 1 === 0;
}
show = (x) => {
if(x) {
if (this.isInt(x)) {
return ${x}
}
else {
return ${x.toFixed(2)}
}
}
}
其他回答
这是我的:
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;
}
适用于所有情况。
对于浮动
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if (!price.match(decimal)) {
alert('Please enter valid float');
return false;
}
对于整数
var number = /^\d+$/;
if (!price.match(number)) {
alert('Please enter valid integer');
return false;
}
以下是检查值是否为数字或是否可以安全地转换为数字的有效函数:
function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}
对于整数(如果值是浮点,则返回false):
function isInteger(value) {
if ((undefined === value) || (null === value)) {
return false;
}
return value % 1 == 0;
}
这里的效率是,当值已经是数字时,可以避免parseInt(或parseNumber)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。
感谢这里的其他帖子为优化提供了进一步的想法!
这里有Number.isInteger(数字)来检查。在Internet Explorer中不工作,但该浏览器不再使用。如果您需要像“90”这样的字符串作为整数(这不是问题),请尝试Number.isInteger(Number(Number))。“官方”isInteger将9.0视为整数,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number.看起来大多数答案对旧版浏览器都是正确的,但现代浏览器已经进步,实际上支持浮点整数检查。