每隔三个数字字符添加一个逗号

Adding a comma at every third number character

本文关键字:一个 添加 三个 数字字符      更新时间:2023-09-26

在我的代码中,我有一个变量myCash,它使用javaScript的innerHTML打印到h1元素中。我在网上找到了一个函数,它在数字末尾的每三个字符后面加一个逗号,这样数字更容易阅读。我已经尝试了几个小时,现在将变量myCash发送到函数中,然后将其打印在屏幕上。我无法让它工作。

我试过在页面加载后或按下按钮将新变量提醒到屏幕上,但我一无所获,警报甚至不起作用。这是逗号插入函数:

function commaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    amount = new String(amount);
    var a = amount.split('.',2)
    var d = a[1];
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3)
    {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

现在,当我想改变我的变量时,我已经尝试了几种不同的方法,包括:

var newMyCash = commaFormatted(myCash); alert(newMyCash);

这个:

alert(commaFormatted(myCash);

其中myCash当然等于某个大数;

这毫无作用!我在这里做错了什么??

此外,

尝试将其作为一个替代品,并尝试提醒响应:

http://phpjs.org/functions/number_format:481

你在浏览器的控制台(通常是f12)中看到任何错误吗?

这不是我的函数,但我希望它能帮助你。

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;
}

用法:

var newMyCash = addCommas( myCash ); alert( newMyCash );

来源:http://www.mredkj.com/javascript/nfbasic.html

您很可能没有传递函数所期望的包含小数的数字。

工作演示