如何判断一个数字是float
还是integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
如何判断一个数字是float
还是integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
其实并不需要这么复杂。一个整数的parseFloat()和parseInt()等价的数字值是相同的。因此,你可以像这样做:
function isInt(value){
return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}
那么
if (isInt(x)) // do work
function is_int(value){ return !isNaN(parseInt(value * 1) }
<html>
<body>
<form method="post" action="#">
<input type="text" id="number_id"/>
<input type="submit" value="send"/>
</form>
<p id="message"></p>
<script>
var flt=document.getElementById("number_id").value;
if(isNaN(flt)==false && Number.isInteger(flt)==false)
{
document.getElementById("message").innerHTML="the number_id is a float ";
}
else
{
document.getElementById("message").innerHTML="the number_id is a Integer";
}
</script>
</body>
</html>
这是检查整数和浮点数的最终代码
function isInt(n) {
if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
return true;
} else {
return false;
}
}
或者
function isInt(n) {
return typeof n == 'number' && Math.Round(n) % 1 == 0;
}
试试这个
let n;
return (n = value % 1) !== 0 && !isNaN(n);
当返回值为false时,意味着输入值为浮点数或浮点字符串,否则输入值为整数数或整数字符串。
基本上需要检查精度值是否不等于零。
另一个是检查正确的字符串数字。
const integerCheck = (num) => {
const isInt = (n) => Number(n) === n && n % 1 === 0
const isFloat = (n) => Number(n) === n && n % 1 !== 0
return (isInt(num) || !isFloat(num))
}
console.log( integerCheck('23.3') );
对于整数,我使用这个
function integer_or_null(value) {
if ((undefined === value) || (null === value)) {
return null;
}
if(value % 1 != 0) {
return null;
}
return value;
}
try this one
function amountcheck()
{
var dpamt=$('#dpamt').val()/5000;
var ints=dpamt.toString();
var isint=ints.split('.');
if(isint[1]>0)
{
alert('float value');
return false;
}
else
{
alert('int value');
}
}
YourJS提供了以下两个函数,适用于所有数字,包括返回false
的-Infinity
和Infinity
:
function isFloat(x) {
return typeOf(x, 'Number') && !!(x % 1);
}
function isInt(x) {
return typeOf(x, 'Number') && x % 1 == 0;
}
由于typeOf()
是YourJS内部函数,如果您想使用这些定义,您可以在此处下载仅包含这些函数的版本:http://yourjs.com/snippets/build/34
if(object instanceof Number ){
if( ((Number) object).doubleValue() % 1 == 0 ){
//your object is an integer
}
else{
//your object is a double
}
}
<nit-pick>
JavaScript没有不同的整数和浮点数字类型。在JavaScript中每个数字都只是一个Number
。</nit-pick>
- Matt Ball1.0
是整型还是浮点型? - vol7ron