最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check if numbers in JavaScript is in the range of int in Java (–2147483648 < n < 2147483647) - Stack Overflow

programmeradmin0浏览0评论

What's he correct way to validate JavaScript numbers as Java int?

  –2147483648 < n < 2147483647

 IsNumeric(2147483648) --> true: which is > int
 parseInt("2147483648") --> 2147483648 : which is > int

What's he correct way to validate JavaScript numbers as Java int?

  –2147483648 < n < 2147483647

 IsNumeric(2147483648) --> true: which is > int
 parseInt("2147483648") --> 2147483648 : which is > int
Share Improve this question asked Oct 22, 2014 at 9:42 RiadhRiadh 1,1963 gold badges15 silver badges25 bronze badges 2
  • Show us some code (function), have you tried something ? – Christophe Roussy Commented Oct 22, 2014 at 9:45
  • I tried ($("#field").val() > 2147483647)... – Riadh Commented Oct 22, 2014 at 10:22
Add a ment  | 

4 Answers 4

Reset to default 7

Assuming that the range of integers in Java is actually "–2147483648 <= n <= 2147483647", the expression ((+a)|0) == a will work as specified.

  • +a evaluates the expression a as a number;
  • |0 converts the number to 32-bit integer

The parison will fail, when a is not exactly representable by an 32-bit integer.

Just test the number in an if?

var number = 1234567;
if (Number.isInteger(number)) && number > -2147483648 && number < 2147483647)
{
    console.log("It is a valid integer!");
}

as a function :

function isValidInt32(number){
   return Number.isInteger(number) && number > -2147483648 && number < 2147483647; 
}

For floating point values, if we want an integer, but allows a value ending in ".0":

isInt32(state) {
    if(!(/^([+-]?[1-9]\d*|0).[0]$/.test(state))
        && !(/^([+-]?[1-9]\d*|0)$/.test(state))) {
        return false;
    }
    const view = new DataView(new ArrayBuffer(32));
    view.setInt32(1, state);
    return Number.parseInt(state) === view.getInt32(1);
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论