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

javascript - Format Amount field with comma and decimal - Stack Overflow

programmeradmin0浏览0评论

How would I format amount field with ma and decimal?
I am able to get mas but this function does not allow decimal in the field.

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
    event.preventDefault();
  }

  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });
});

How would I format amount field with ma and decimal?
I am able to get mas but this function does not allow decimal in the field.

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
    event.preventDefault();
  }

  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });
});
Share Improve this question edited Sep 6, 2013 at 12:21 NDM 6,8403 gold badges41 silver badges54 bronze badges asked Sep 6, 2013 at 12:05 Himanshu YadavHimanshu Yadav 13.6k49 gold badges170 silver badges295 bronze badges 1
  • 2 Possible duplicate "How can I format numbers as money in JavaScript?"? – insertusernamehere Commented Sep 6, 2013 at 12:10
Add a ment  | 

1 Answer 1

Reset to default 4

Is this what you had in mind?

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
    event.preventDefault();
  }

  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/([0-9])([0-9]{2})$/, '$1.$2')  
      .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",")
    ;
  });
});

You can test it here: http://jsfiddle/fXrv2/

发布评论

评论列表(0)

  1. 暂无评论