私はサイトで作業しています。価格の入力フィールドがあります。次のような価格値をフォーマットする必要があります。
if a user enter "1000000" it should replace with "1,000,000" is it possible?
何か助けはありますか?
私はサイトで作業しています。価格の入力フィールドがあります。次のような価格値をフォーマットする必要があります。
if a user enter "1000000" it should replace with "1,000,000" is it possible?
何か助けはありますか?
次のようなカスタム関数が必要です:
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;
}
次のようにできます。
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[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;
}