15

次の関数を使用して、ユーザータイプとして数値をフォーマットしています。3つの数字ごとにコンマを挿入します。例:45696.36になり45,696.36ます。

しかし、私はそれに問題が発生しました。小数点以下の数字が3桁より長い場合、コンマが追加され始めます。例:1136.6696になり1,136.6,696ます。

これは私の機能です:

$.fn.digits = function(){
  return this.each(function() {
    $(this).val( $(this).val().replace(/[^0-9.-]/g, '') );
    $(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
  }) 
}

小数点以下のコンマの配置を停止するようにこれを修正するにはどうすればよいですか?私はjQuery1.8を使用しています。ありがとう!

4

2 に答える 2

54

文字列を ' .' 文字で分割し、最初のセクションのみでコンマ変換を実行することで、これを実現できます。

function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n= yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //Combines the two sections
    return n.join(".");
}

ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696

于 2012-12-28T19:58:18.670 に答える
2

私はaccounting.js libを使用しています:

accounting.format(1136.6696, 4) // 1,136.6696
于 2016-09-30T21:26:10.653 に答える