0

重複の可能性:
JavaScript で数値を金額としてフォーマットするにはどうすればよいですか?

私はサイトで作業しています。価格の入力フィールドがあります。次のような価格値をフォーマットする必要があります。

if a user enter "1000000" it should replace with "1,000,000" is it possible?

何か助けはありますか?

4

3 に答える 3

2

次のようなカスタム関数が必要です:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
于 2012-10-16T10:32:27.710 に答える
1

次のようにできます。

function numberWithCommas(n) {
    var parts=n.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

デモ: http://jsfiddle.net/e9AeK/

于 2012-10-16T10:33:54.030 に答える
1

大樹のコードを少し修正。ユーザーが1000000を入力すると、 1,000,000が生成されるためです。ただし、ユーザーがBackspaceキーを使用して「0」を削除すると、機能しません。

function addPriceFormat()
{
    var numb='';
    nStr = document.getElementById('txt').value;
    my = nStr.split(',');
    var Len = my.length;
    for (var i=0; i<Len;i++){numb = numb+my[i];}
    x = numb.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1)) 
    {
       x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    formated = x1 + x2;
    document.getElementById('txt').value = formated;
}
于 2012-10-16T11:36:25.417 に答える