I have an html text box where I want to limit the numbers after decimal to 4. After an operation it can be achieved using toFixed() but while the user inputs the text is there any way out.
Please guide me.
I have an html text box where I want to limit the numbers after decimal to 4. After an operation it can be achieved using toFixed() but while the user inputs the text is there any way out.
Please guide me.
Did you Try a REGEX?
The Regex would look like
/^[0-9]+.[0-9]{4}$/
where {4} says that Length after .
would be 4
Define REGEX:
var regex1=/^[0-9]+.[0-9]{4}$/;var yourtextfromTextBox= textBox.text();yourtextfromTextBox.match(regex1);
Try this
function decimal_only(e) {
var charCode = (e.which) ? e.which : window.event.keyCode
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46) { //Now Check The Decimal only allow 1 decimal
if (e.value.indexOf('.') > -1) {
return false;
}
}
return true;
}
use this function on textbox event onkeypress.
like
onkeypress="return decimal_only(this)"
this will only allow 1 decimal and integer values to users
Just an idea: jsFiddle live demo
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Round to 4 Decimal Places</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
$('#input').keypress(function(){
try {
val = $(this).val().split('.');
if(val[1] > 999) return false;
}catch(e){}
})
});
</script>
</head>
<body>
<p>Type a decimal number in the TextBox, limited to 4 decimals</p>
<input id="input" type="text" />
</body>
</html>
Of course, this works only for .
, this could be improved by allow only numbers, and check for ,
too.
Here's a sample: http://jsfiddle.net/Regisc/5yber/
This use a regexp to validate the content of the input and make use of this function in order to take carret into account.
Tested under Chrome (dev)