1

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
Riadh
  • 852
  • 1
  • 10
  • 22

4 Answers4

5

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 comparison will fail, when a is not exactly representable by an 32-bit integer.

Aki Suihkonen
  • 18,135
  • 1
  • 34
  • 55
0

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!");
}
Jerodev
  • 31,061
  • 11
  • 83
  • 102
  • Thank you for the proposition, that what I have done to resolve the issue temporary... but I'm looking for more effective solution – Riadh Oct 22 '14 at 10:23
0

as a function :

function isValidInt32(number){
   return Number.isInteger(number) && number > -2147483648 && number < 2147483647; 
}
MSS
  • 3,247
  • 23
  • 27
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);
}