function isNumber(n) {
var j = n.trim();
return (j % 1 === 0 && j != "");
}
My function still returns true if the inputted value is "14.0". It should only allow whole numbers without any decimal.
function isNumber(n) {
var j = n.trim();
return (j % 1 === 0 && j != "");
}
My function still returns true if the inputted value is "14.0". It should only allow whole numbers without any decimal.
You can use regex for this
function isWhole(n) {
return /^\d+$/.test(n);
}
$("#number").change(function() {
if (isWhole($(this).val())) {
$(".error").hide();
} else {
$(".error").show();
}
});
.error {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" name="number" />
<p class="error">Whole numbers only</p>
Try treating it as a string and use the match function with regex to see if there is a decimal there. You can use yourVariable.match (/[0-9]*(\.)[0-9]*/)
. It will return true if there is a decimal there.
Abuse the round() function. That will get rid of the garbage:
function isNumber(n) {
if(Math.round(n)==n && n.length==(Math.round(n)).length)
return n;
else return false;
}
Essentially this function returns false if the number is not an integer, and returns the exact integer if it is an integer.
Input 14.0 should return false
Input 13.5 should return false
Input 13 should return 13.