最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Add thousand separator with JavaScript on keyup event - Stack Overflow

programmeradmin5浏览0评论

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 value 1.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
 |  Show 4 more ments

1 Answer 1

Reset to default 8

Splitting 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'>

发布评论

评论列表(0)

  1. 暂无评论