I am passing in a parameter called value. I\'d like to know if value is a float. So far, I have the following:
if (!isNaN(value))
{
alert(\'this is a num
use this jquery code
<script>
$(document).ready(function () {
$(".allow_only_float").keypress(function (e) {
if (e.which != 46 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();//return false;
}
var avg = $('#<%=txtAverage.ClientID%>').val();
var idx = avg.indexOf(".");
if (idx > -1 && e.which == 46) {
e.preventDefault();//return false;
}
});
});
</script>
<body>
<input type='text' class='allow_only_float'>
</body>
To check if a string is an integer or a float
function isFloat(n) {
return parseFloat(n.match(/^-?\d*(\.\d+)?$/))>0;
}
//alert(isFloat("3.444"));
This function returns the numeric value of a string regardless if int or float
function getNumericVal(str) {
if(isNaN(str)) return;
try {return parseFloat(str);}
catch(e) {return parseInt(str);}
}
straight forward:
if (parseFloat(value).toString() === value.toString()) {
...
}
Following functions also check for format. E.g. JavaScript native parseInt
and parseFloat
functions also parse strings containing non numeric characters, and functions above have consequences of this.
// For example, following code will work
var n = parseInt('123asd');
n == 123
These functions will return false
for such string.
function isFloat(val) {
var floatRegex = /^-?\d+(?:[.,]\d*?)?$/;
if (!floatRegex.test(val))
return false;
val = parseFloat(val);
if (isNaN(val))
return false;
return true;
}
function isInt(val) {
var intRegex = /^-?\d+$/;
if (!intRegex.test(val))
return false;
var intVal = parseInt(val, 10);
return parseFloat(val) == intVal && !isNaN(intVal);
}
function checkFloat(value) {
let parsed = Number.parseFloat(value);
return (!Number.isNaN(parsed)) && (!Number.isInteger(parsed))
}