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