如何在格式化货币时删除JavaScript中的最后一个逗号?

时间:2014-10-07 11:56:02

标签: javascript jquery

我有代码:

function money_format(number)   {
    //if (isNaN(number)) return "";
    var str = new String(number);
    var result = "" , len = str.length;
    for(var i=len-1;i>=0;i--) {
        if ((i+1)%3 == 0 && i+1!= len) {
                result += ",";

        }
        result += str.charAt(len-1-i);
    }
    return result;
}

事件:

$("#number").keyup(function() {
    var tot = 0;
    tot     = $(this).val().substr(0).replace(/\./g,'')
    $(this).val(money_format(tot));
    $("#msg").html(tot);
});

请问我的jsfiddle:http://jsfiddle.net/bx5bu3j0/

如何删除最后一个昏迷??

喜欢:1.000.000,01

3 个答案:

答案 0 :(得分:1)

我建议简单地避免使用数字的浮点部分:

function money_format(number) {
    // use toString() to create a string,
    // split the string to an integer and float portion:
    var numbers = number.toString().split('.'),
        integerPortion = numbers[0],
    // if there is a float portion, we'll use it, otherwise set it to false:
        floatPortion = numbers[1] ? numbers[1] : false,
        result = "",
        len = integerPortion.length;

    for (var i = len - 1; i >= 0; i--) {
        if ((i + 1) % 3 === 0 && i + 1 != len) {
            result += ",";
        }
        result += integerPortion.charAt(len - 1 - i);
    }

    // return the concatenated 'result' with either the float portion (if there is/was one)
    // or an empty string, if there was not:
    return result + (floatPortion ? '.' + floatPortion : '');
}

console.log(money_format(12345678.98));

JS Fiddle demo

答案 1 :(得分:1)

如果您使用字符串替换,当它到达任何非数字时停止,您可以将逗号添加到带小数的字符串 -

function addCommas(n){
    var rx=  /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function(w){
        while(rx.test(w)){
            w= w.replace(rx, '$1,$2');
        }
        return w;
    });
}
var n=123456789.091;

addCommas(n)

/*  returned value: (String)
123,456,789.091
*/

答案 2 :(得分:0)

您可以使用lastIndexOf找到要删除的逗号的索引,然后使用substr将其从字符串中删除。

这是a sample fiddle

function money_format(number)   {

    var str = new String(number);    
    var index = str.split('').lastIndexOf(",");    
    /* remove if comma found */
    if(index != -1) {
        str = str.substr(0, index) + str.substr(index+1);               
    }        
    return str;
}

alert(money_format("1.000.000,01"));