检查一个数字是否有一个小数/是一个整数

时间:2022-04-12 16:57:15

I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer). For instance,

我正在寻找一种简单的JavaScript方法来检查一个数字是否有小数点(以便确定它是否是一个整数)。例如,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}

17 个解决方案

#1


582  

Using modulus will work:

使用模量将工作:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

注意,这是基于数字的数值,而不考虑格式。它处理含有与整数相同的固定小数点的整数值字符串:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5

#2


34  

Or you could just use to find out if it is NOT a decimal:

或者你可以用它来确定它是不是小数:

string.indexOf(".")==-1;

#3


19  

The most common solution is to strip the integer portion of the number and compare it to zero like so:

最常见的解决方法是将数字的整数部分去掉,然后像这样将其与0进行比较:

function Test()
{
     var startVal = 123.456
     alert( (startVal - Math.floor(startVal)) != 0 )
}

#4


17  

//How about byte-ing it?

/ / byte-ing怎么样吗?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

我总是觉得javascript中的位操作符不好

they hardly get any exercise.

他们几乎没有锻炼。

#5


15  

Simple, but effective!

简单,但有效!

Math.floor(number) == number;

#6


14  

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

isinteger()是ES6标准的一部分,在IE11中不受支持。

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

对于NaN、∞和非数值参数,它返回false,而x % 1 != 0返回true。

#7


4  

var re=/^-?[0-9]+$/;
var num=10;
re.test(num);

#8


2  

function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}

#9


2  

number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

Pretty cool and works for things like XX.0 too! It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)

非常酷,适用于XX.0之类的东西!它可以工作,因为Math.floor()可以去掉任何一个小数,如果它有一个,那么如果底数不同于原始数字,我们知道它是一个小数!并且没有字符串转换:)

#10


1  

parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

当传递一个数字时,parseInt()只返回数字作为int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

#11


1  

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

以下是我的警卫库(受David Herman的有效JavaScript启发)的摘录:

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

#12


1  

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

你可以把它乘以10,然后用10做一个“模块化”操作/除法,然后检查这两个操作的结果是否为零。这两个操作的结果将给出小数点后的第一个数字。如果结果等于零,那么这个数就是一个整数。

if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}

#13


0  

Function for check number is Decimal or whole number

函数的作用是:校验数为十进制或整数

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

#14


0  

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

将数字字符串转换为数组,按小数点分割。然后,如果数组只有一个值,这意味着字符串中没有小数。

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

这样你也可以知道整数和小数的实际值。一个更高级的例子是。

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}

#15


0  

$('.rsval').bind('keypress', function(e){  
        var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
        var keynum = (!window.event) ? e.which : e.keyCode; 
        var val = this.value;
        var numlenght = val.length;
        var splitn = val.split("."); 
        var decimal = splitn.length;
        var precision = splitn[1];
        var startPos = this.selectionStart;
        var decimalIndex = val.indexOf('.'); 
        if(decimal == 2) {  
            if(decimalIndex < startPos){
                if(precision.length >= 2){
                  e.preventDefault();  
                }
            } 
        } 
        if( keynum == 46 ){  
            if(startPos < (numlenght-2)){
                e.preventDefault(); 
            }
            if(decimal >= 2) { e.preventDefault(); }  
        } 
        if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
            e.preventDefault();    
  });

#16


0  

function isDecimal(num) {
  return (num !== parseInt(num, 10));
}

#17


0  

You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:

您可以使用位操作,不改变的值(^ 0或~ ~)丢弃小数部分,可用于舍入。四舍五入后,与原始值进行比较:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true

#1


582  

Using modulus will work:

使用模量将工作:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

注意,这是基于数字的数值,而不考虑格式。它处理含有与整数相同的固定小数点的整数值字符串:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5

#2


34  

Or you could just use to find out if it is NOT a decimal:

或者你可以用它来确定它是不是小数:

string.indexOf(".")==-1;

#3


19  

The most common solution is to strip the integer portion of the number and compare it to zero like so:

最常见的解决方法是将数字的整数部分去掉,然后像这样将其与0进行比较:

function Test()
{
     var startVal = 123.456
     alert( (startVal - Math.floor(startVal)) != 0 )
}

#4


17  

//How about byte-ing it?

/ / byte-ing怎么样吗?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

我总是觉得javascript中的位操作符不好

they hardly get any exercise.

他们几乎没有锻炼。

#5


15  

Simple, but effective!

简单,但有效!

Math.floor(number) == number;

#6


14  

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

isinteger()是ES6标准的一部分,在IE11中不受支持。

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

对于NaN、∞和非数值参数,它返回false,而x % 1 != 0返回true。

#7


4  

var re=/^-?[0-9]+$/;
var num=10;
re.test(num);

#8


2  

function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}

#9


2  

number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

Pretty cool and works for things like XX.0 too! It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)

非常酷,适用于XX.0之类的东西!它可以工作,因为Math.floor()可以去掉任何一个小数,如果它有一个,那么如果底数不同于原始数字,我们知道它是一个小数!并且没有字符串转换:)

#10


1  

parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

当传递一个数字时,parseInt()只返回数字作为int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

#11


1  

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

以下是我的警卫库(受David Herman的有效JavaScript启发)的摘录:

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

#12


1  

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

你可以把它乘以10,然后用10做一个“模块化”操作/除法,然后检查这两个操作的结果是否为零。这两个操作的结果将给出小数点后的第一个数字。如果结果等于零,那么这个数就是一个整数。

if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}

#13


0  

Function for check number is Decimal or whole number

函数的作用是:校验数为十进制或整数

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

#14


0  

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

将数字字符串转换为数组,按小数点分割。然后,如果数组只有一个值,这意味着字符串中没有小数。

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

这样你也可以知道整数和小数的实际值。一个更高级的例子是。

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}

#15


0  

$('.rsval').bind('keypress', function(e){  
        var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
        var keynum = (!window.event) ? e.which : e.keyCode; 
        var val = this.value;
        var numlenght = val.length;
        var splitn = val.split("."); 
        var decimal = splitn.length;
        var precision = splitn[1];
        var startPos = this.selectionStart;
        var decimalIndex = val.indexOf('.'); 
        if(decimal == 2) {  
            if(decimalIndex < startPos){
                if(precision.length >= 2){
                  e.preventDefault();  
                }
            } 
        } 
        if( keynum == 46 ){  
            if(startPos < (numlenght-2)){
                e.preventDefault(); 
            }
            if(decimal >= 2) { e.preventDefault(); }  
        } 
        if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
            e.preventDefault();    
  });

#16


0  

function isDecimal(num) {
  return (num !== parseInt(num, 10));
}

#17


0  

You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:

您可以使用位操作,不改变的值(^ 0或~ ~)丢弃小数部分,可用于舍入。四舍五入后,与原始值进行比较:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true