숫자의 소수점 이하/정수 여부를 확인합니다.
자바스크립트에서 숫자가 소수점 이하인지(정수인지 아닌지를 판단하기 위해) 쉽게 확인할 수 있는 방법을 찾고 있습니다.예를 들어.
23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
계수를 사용하면 다음과 같이 동작합니다.
num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5
이것은 형식에 관계없이 숫자의 수치를 기반으로 합니다.고정 소수점을 가진 정수를 포함하는 숫자 문자열을 정수와 동일하게 취급합니다.
'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger()는 ES6 표준의 일부이며 IE11에서는 지원되지 않습니다.
에 대해 false가 반환됩니다.NaN
,Infinity
및 non-disclused 인수,x % 1 != 0
true를 반환합니다.
또는 이것을 사용하여 소수점이 아닌지를 확인할 수도 있습니다.
string.indexOf(".") == -1;
심플하지만 효과적!
Math.floor(number) === number;
가장 일반적인 해결책은 다음과 같이 숫자의 정수 부분을 제거하고 0과 비교하는 것입니다.
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
//바이트 입력은 어떻습니까?
Number.prototype.isInt= function(){
return this== this>> 0;
}
javascript의 비트 오퍼레이터에게는 항상 미안한 마음이 듭니다.
그들은 거의 운동을 하지 않는다.
Number.isSafeInteger(value);
JavaScript에서는 isSafeInteger()는 값이 안전한 정수인지 여부를 나타내는 부울 값을 반환하기 위해 사용되는 Number 메서드입니다.즉, 반올림 없이 IEEE-754 배 정밀도로 정확하게 나타낼 수 있는 정수 값입니다.
Number.isInteger()
아마 가장 간결할 겁니다.정수일 경우 true를 반환하고, 정수가 아닐 경우 false를 반환합니다.
number = 20.5
if (number == Math.floor(number)) {
alert("Integer")
} else {
alert("Decimal")
}
꽤 멋지고 XX.0에도 잘 어울려요!Math.floor()가 있으면 소수점 이하를 잘라내기 때문에 바닥이 원래 숫자와 다르면 소수점 이하임을 알 수 있습니다.문자열 변환 없음:)
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
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;
}
parseInt(num) === num
번호를 통과하면parseInt()
는 int: 로서 번호를 반환합니다.
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
숫자 문자열을 배열로 변환하고 소수점으로 나눕니다.배열에 값이 하나만 있는 경우 문자열에 소수점이 없음을 의미합니다.
if(!number.split(".")[1]){
//do stuff
}
이렇게 하면 실제로 정수와 소수점이 무엇인지 알 수 있습니다. 더 고급화된 예가 될 수 있습니다.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
값이 문자열(예: from)인 경우 다음을 사용합니다.<input
):
Math.floor(value).toString() !== value
덧붙이다.toString()
바닥으로 하다value == "1."
(종료에는 10진수 구분자 또는 다른 문자열이 있습니다).또한.Math.floor
항상 어떤 값을 반환하기 때문에.toString()
실패하지 않습니다.
다음은 내 가드 라이브러리에서 발췌한 것이다(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
10을 곱한 다음 10을 사용하여 "모듈로" 연산/분할을 수행하고 두 연산의 결과가 0인지 확인할 수 있습니다.이 두 번의 연산의 결과로 소수점 뒤의 첫 번째 숫자가 표시됩니다.결과가 0일 경우 숫자는 정수입니다.
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
( 「 」 )을 사용할 수 있습니다.^ 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
function isWholeNumber(num) {
return num === Math.round(num);
}
이게 너한테 좋을까?
regex를 사용하여 번호에 쉼표가 있는지 확인하고 없으면 쉼표와 스트라이프를 추가합니다.
var myNumber = '50';
function addCommaStripe(text){
if(/,/.test(text) == false){
return text += ',-';
} else {
return text;
}
}
myNumber = addCommaStripe(myNumber);
10진수 스텝의 카운터를 사용하는 경우, 다음과 같이 숫자가 반올림인지 아닌지를 확인하는 것은 실제로 실패합니다.따라서 숫자 형식은 소수점 이하 9자리(더 많을 수 있음)로 지정하는 것이 가장 안전할 수 있으며, 9자리 0으로 끝나면 정수입니다.
const isRound = number => number.toFixed(9).endsWith('000000000');
for (let counter = 0; counter < 2; counter += 0.1) {
console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}
체크 번호에 대한 함수는 10진수 또는 정수입니다.
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}
언급URL : https://stackoverflow.com/questions/2304052/check-if-a-number-has-a-decimal-place-is-a-whole-number
'programing' 카테고리의 다른 글
문자열로 표시되도록 전달된 JSON 열 - Larabel - Vuejs2 (0) | 2022.10.23 |
---|---|
C의 등식을 위한 구조를 어떻게 비교합니까? (0) | 2022.10.23 |
오류: 테이블 " "에 대해 사용자 "@"에 대해 명령 거부됨 (0) | 2022.10.23 |
플라스크에 http 헤더를 넣는 방법 (0) | 2022.10.23 |
Java, Apache kafka에서 항목의 메시지 수를 가져오는 방법 (0) | 2022.10.23 |