I am using the following JavaScript function to add thousand separator for a input number on keyup event.
$("#inputId").on('keyup', function(evt){
if (evt.which != 110 && evt.which != 190){
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
Most of the cases this function is working as expected, but the only issue is the input field does not accept zero after the decimal point (for example 10.01) but it does accept numbers like 10.25 . I can't figure out the reason for this behavior. Any idea?
Thanks.
I am using the following JavaScript function to add thousand separator for a input number on keyup event.
$("#inputId").on('keyup', function(evt){
if (evt.which != 110 && evt.which != 190){
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
Most of the cases this function is working as expected, but the only issue is the input field does not accept zero after the decimal point (for example 10.01) but it does accept numbers like 10.25 . I can't figure out the reason for this behavior. Any idea?
Thanks.
Share Improve this question edited Feb 9, 2017 at 5:48 Ashish Bahl 1,5021 gold badge18 silver badges28 bronze badges asked Feb 9, 2017 at 4:40 LakmalLakmal 2571 gold badge10 silver badges25 bronze badges 9-
parsing would remove the
0
, since which doesn't have any value1.0
=>1
– Pranav C Balan Commented Feb 9, 2017 at 4:47 -
1
What does
parseFloat(x,10)
do? MDN says it has only one argument – Flying Gambit Commented Feb 9, 2017 at 4:48 -
parseFloat
doesn't have any radix argument.... so adding second argument doesn't make any sense – Pranav C Balan Commented Feb 9, 2017 at 4:49 - Out of curiosity, What exactly is a thousand separator ? – Flying Gambit Commented Feb 9, 2017 at 4:53
- 1 @FlyingGambit toLocaleString() will add the thousand separator(for me ","). – Lakmal Commented Feb 9, 2017 at 4:56
1 Answer
Reset to default 8Splitting on the decimal would work. Something like this. Note this is very basic starting point and does not account for the different separators in other countries/systems (ie: 10.000,00)
<script>
var myinput = document.getElementById('myinput');
myinput.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
<input id="myinput" type="text'>