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
4 Answers
Reset to default 7Assuming 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);
}