2

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
  • 1,088
  • 2
  • 12
  • 25

4 Answers4

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

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
  • I checked it in jsconsole.com – Aki Suihkonen Oct 23 '14 at 05:38
  • Wouldn't you want to do the comparison using `===` since the question specified that the value should be a JavaScript Number, not a string? I do like the bitwise method you're using; I actually came here to add an answer for it if no one else had. – aecend Jun 12 '23 at 18:40
  • Yes, `===` can be used for comparison, if the intent is to also guarantee that the variable was originally of number type, not just representable as int32. – Aki Suihkonen Jun 14 '23 at 04:10
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
  • 32,252
  • 11
  • 87
  • 108
  • 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,520
  • 24
  • 29
0

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);
}