Programing

문자열이 양의 정수인지 확인

lottogame 2020. 5. 14. 07:57
반응형

문자열이 양의 정수인지 확인


JavaScript의 문자열이 양의 정수인지 확인하는 가장 간단한 오류 방지 테스트를 원합니다.

isNaN(str)정수가 아닌 모든 종류의 값에 대해 true를 반환하고 parseInt(str)"2.5"와 같이 부동 문자열에 대한 정수를 반환합니다. 그리고 jQuery 플러그인도 사용하고 싶지 않습니다.


두 가지 답변 :

  • 파싱 ​​기반

  • 정규식

두 경우 모두, 내가 포함 "양의 정수"를 해석 한 것을 참고 0비록은 0긍정적 없습니다. 당신이 허용하지 않으려면 메모를 포함합니다 0.

파싱 ​​기반

합리적인 범위의 값에서 정규화 된 십진 정수 문자열이되도록하려면 다음을 수행하십시오.

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

또는 공백과 선행 0을 허용하려는 경우 :

function isNormalInteger(str) {
    str = str.trim();
    if (!str) {
        return false;
    }
    str = str.replace(/^0+/, "") || "0";
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

라이브 테스트 베드 (앞에 0이나 공백이없는 경우) :

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}
function gid(id) {
    return document.getElementById(id);
}
function test(str, expect) {
    var result = isNormalInteger(str);
    console.log(
        str + ": " +
        (result ? "Yes" : "No") +
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
    );
}
gid("btn").addEventListener(
    "click",
    function() {
        test(gid("text").value);
    },
    false
);
test("1", true);
test("1.23", false);
test("1234567890123", true);
test("1234567890123.1", false);
test("0123", false); // false because we don't handle leading 0s
test(" 123 ", false); // false because we don't handle whitespace
<label>
  String:
  <input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

(라이브 테스트 베드 앞의 0과 공백에 대한 처리) :

function isNormalInteger(str) {
    str = str.trim();
    if (!str) {
        return false;
    }
    str = str.replace(/^0+/, "") || "0";
    var n = Math.floor(Number(str));
    return String(n) === str && n >= 0;
}
function gid(id) {
    return document.getElementById(id);
}
function test(str, expect) {
    var result = isNormalInteger(str);
    console.log(
        str + ": " +
        (result ? "Yes" : "No") +
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
    );
}
gid("btn").addEventListener(
    "click",
    function() {
        test(gid("text").value);
    },
    false
);
test("1", true);
test("1.23", false);
test("1234567890123", true);
test("1234567890123.1", false);
test("0123", true);
test(" 123 ", true);
<label>
  String:
  <input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

허용하지 않으려면로 0변경 >= 0하십시오 > 0. (또는 선행 0을 허용하는 버전 || "0"에서는 replace라인을 제거하십시오 .)

작동 방식 :

  1. 공백과 선행 0을 허용하는 버전에서 :

    • str = str.trim(); 앞뒤 공백을 제거합니다.
    • if (!str) 빈 문자열을 잡아서 나머지 작업을 수행 할 때 아무런 의미가 없습니다.
    • str = str.replace(/^0+/, "") || "0"; 문자열에서 모든 선행 0을 제거합니다. 그러나 빈 문자열이되면 단일 0을 복원합니다.
  2. Number(str): str숫자로 변환 ; 그 수는 소수 부분을 가질 수 있거나 또는 일 수있다 NaN.

  3. Math.floor: 숫자를 자릅니다 (소수 부분 잘라 냄).

  4. String(...): 결과를 다시 정상 10 진수 문자열로 변환합니다. 실제로 큰 숫자의 경우 과학 표기법으로 이동 하여이 접근법을 깨뜨릴 수 있습니다. (스 플리트가 어디에 있는지, 세부 사항이 spec에 있는지 잘 모르겠지만 , 전체 숫자의 경우 IEEE-754와 같이 21 자리를 초과 한 시점에 있다고 생각합니다. 배정도 숫자는 대략 15 자리의 정밀도 만 갖습니다.)

  5. ... === str: 원래 문자열과 비교합니다.

  6. n >= 0: 긍정적인지 확인하십시오.

이것은 "+1"입력에서, 과학적 표기법의 입력에서 String(...)스테이지 에서 동일한 과학적 표기법으로 다시 돌아 가지 않으며 JavaScript가 사용하는 숫자 종류 (IEEE-754 배정도 이진 부동 소수점)에 대해서는 실패합니다. 주어진 구문과 다른 값에 더 가까운 구문을 정확하게 나타낼 수 없습니다 (예를 들어, 9,007,199,254,740,992 이상의 많은 정수 포함; 1234567890123456789실패). 전자는 쉬운 해결책이며, 후자는 그다지 많지 않습니다.

정규식

다른 접근법은 정규 표현식을 통해 문자열의 문자를 테스트하는 것입니다. 목표는 선택 사항 +다음 0에 일반 10 진수 형식의 문자열을 허용하는 것입니다 (예 :).

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}

라이브 테스트 베드 :

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}
function gid(id) {
    return document.getElementById(id);
}
function test(str, expect) {
    var result = isNormalInteger(str);
    console.log(
        str + ": " +
        (result ? "Yes" : "No") +
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
    );
}
gid("btn").addEventListener(
    "click",
    function() {
        test(gid("text").value);
    },
    false
);
test("1", true);
test("1.23", false);
test("1234567890123", true);
test("1234567890123.1", false);
test("0123", false); // false because we don't handle leading 0s
test(" 123 ", false); // false because we don't handle whitespace
<label>
  String:
  <input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

작동 방식 :

  1. ^: 문자열의 일치 시작

  2. \+?: 단일 옵션을 허용합니다 +(원치 않는 경우 제거)

  3. (?:...|...): 캡처 그룹을 작성하지 않고 다음 두 옵션 중 하나를 허용하십시오.

    1. (0|...): 0스스로 허용 ...

    2. (...|[1-9]\d*): ... 또는 010 진수 이외의 숫자로 시작하는 숫자.

  4. $: 문자열 끝과 일치합니다.

0긍정적이지 않기 때문에 허용하지 않으려면 정규 표현식이 그대로됩니다 /^\+?[1-9]\d*$/(예 : 허용해야하는 대체 항목을 잃을 수 있음 0).

당신이 선행 0 (0123, 00524)을 허용 할 경우, 바로 교대 교체 (?:0|[1-9]\d*)로를\d+

function isNormalInteger(str) {
    return /^\+?\d+$/.test(str);
}

공백을 허용하려면 \s*직후 ^\s*바로 앞에 추가하십시오 $.

Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10) to ensure that it's parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we've ensured there isn't any with the regex.


Solution 1

If we consider a JavaScript integer to be a value of maximum 4294967295 (i.e. Math.pow(2,32)-1), then the following short solution will perfectly work:

function isPositiveInteger(n) {
    return n >>> 0 === parseFloat(n);
}

DESCRIPTION:

  1. Zero-fill right shift operator does three important things:
    • truncates decimal part
      • 123.45 >>> 0 === 123
    • does the shift for negative numbers
      • -1 >>> 0 === 4294967295
    • "works" in range of MAX_INT
      • 1e10 >>> 0 === 1410065408
      • 1e7 >>> 0 === 10000000
  2. parseFloat does correct parsing of string numbers (setting NaN for non numeric strings)

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e7"                  : false
"1e7"                   : true
"1e10"                  : false
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/37/


Solution 2

Another way is good for all numeric values which are valid up to Number.MAX_VALUE, i.e. to about 1.7976931348623157e+308:

function isPositiveInteger(n) {
    return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
}

DESCRIPTION:

  1. !isNaN(parseFloat(n)) is used to filter pure string values, e.g. "", " ", "string";
  2. 0 <= ~~n filters negative and large non-integer values, e.g. "-40.1", "129000098131766699";
  3. (!isNaN(parseFloat(n)) && 0 <= ~~n) returns true if value is both numeric and positive;
  4. 0 === n % (...) checks if value is non-float -- here (...) (see 3) is evaluated as 0 in case of false, and as 1 in case of true.

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e10"                 : false
"1e10"                  : true
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/14/


The previous version:

function isPositiveInteger(n) {
    return n == "0" || ((n | 0) > 0 && n % 1 == 0);
}

DEMO: http://jsfiddle.net/5UCy4/2/


Looks like a regular expression is the way to go:

var isInt = /^\+?\d+$/.test('the string');

The modern solution that works in node and across over 90% of all browsers (except IE and Opera Mini) is to use Number.isInteger followed by a simple positive check.

Number.isInteger(x) && x > 0

This was finalized in ECMAScript 2015.

function isPositiveInteger(x) {
    return Number.isInteger(x) && x > 0
}

The Polyfil is:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
    isFinite(value) && 
    Math.floor(value) === value;
};

If you need to support input that might be in string or number form then you can use this function I wrote a large test suite against after all the existing answers (2/1/2018) failed on some form of input.

function isPositiveInteger(v) {
  var i;
  return v && (i = parseInt(v)) && i > 0 && (i === v || ''+i === v);
}

This is almost a duplicate question fo this one:

Validate decimal numbers in JavaScript - IsNumeric()

It's answer is:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

so, a positive integer would be:

function isPositiveInteger(n) {
  var floatN = parseFloat(n);
  return !isNaN(floatN) && isFinite(n) && floatN > 0
      && floatN % 1 == 0;
}

return ((parseInt(str, 10).toString() == str) && str.indexOf('-') === -1);

won't work if you give a string like '0001' though


My function checks if number is +ve and could be have decimal value as well.

       function validateNumeric(numValue){
            var value = parseFloat(numValue);
            if (!numValue.toString().match(/^[-]?\d*\.?\d*$/)) 
                    return false;
            else if (numValue < 0) {
                return false;
            }
            return true;        
        }

Just to build on VisioN's answer above, if you are using the jQuery validation plugin you could use this:

$(document).ready(function() {
    $.validator.addMethod('integer', function(value, element, param) {
        return (value >>> 0 === parseFloat(value) && value > 0);
    }, 'Please enter a non zero integer value!');
}

Then you could use in your normal rules set or add it dynamically this way:

$("#positiveIntegerField").rules("add", {required:true, integer:true});

(~~a == a) where a is the string.


Simply use this

let num = 1.2;
let res;
res = Number.isInteger(num);
console.log(res);

You will get the result in true or false.

If it will be integer then it will return true else it will return false.


Simple

function isInteger(num) {
  return (num ^ 0) === num;
}

console.log(isInteger(1));

You can also extend Number and assign the function to it via prototype.


If you are using HTML5 forms, you can use attribute min="0" for form element <input type="number" />. This is supported by all major browsers. It does not involve Javascript for such simple tasks, but is integrated in new html standard. It is documented on https://www.w3schools.com/tags/att_input_min.asp

참고URL : https://stackoverflow.com/questions/10834796/validate-that-a-string-is-a-positive-integer

반응형