对于大数字,在此本地化函数上强制使用两位小数

时间:2016-04-12 19:15:43

标签: javascript

我有以下函数自动将逗号添加到美国数字表达式,这是一种本地化的方式。我需要对这个功能进行一些小改动。

如果我有160 * 54.08 = 8.652,8作为函数的输入我该怎么做才能将输出显示为8.652,80并带有两个小数位?现在,函数输出为8.652.8

function Numberformat(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;
}

3 个答案:

答案 0 :(得分:0)

检查此答案:https://stackoverflow.com/a/149099/3025534

您可以使用:

  var profits=2489.8237
  profits.toFixed(3) //returns 2489.824 (round up)
  profits.toFixed(2) //returns 2489.82
  profits.toFixed(7) //returns 2489.8237000 (padding)

然后你可以添加'$'的标志。

如果你需要',',千万可以使用:

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

并将其用于:

(123456789.12345).formatMoney(2, '.', ',');

如果你总是要使用'。'和',',你可以将它们从方法调用中移除,该方法将默认为你。

(123456789.12345).formatMoney(2);

如果您的文化中有两个符号翻转(即欧洲人),只需在formatMoney方法中粘贴以下两行:

d = d == undefined ? "," : d, 
t = t == undefined ? "." : t, 

答案 1 :(得分:0)

我会做这样的事情

var n = '1.000,00';

if (wrongFormat(n)) {
  n = n.replace(',', '#');
  n = n.replace('.', ',');
  n = n.replace('#', '.');
}

var val = 1*n;

//do something with val here

答案 2 :(得分:0)

function Numberformat(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : ',0';//if there is no decimal 
                                          //force ",00"
    x2 = x2.length < 3? x2 + "0" : x2;//if length of decimal + delimiter is 
                                      //less than 3 add an extra 0
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

document.body.innerHTML = Numberformat(160 * 54.08);//8.652,80
document.body.innerHTML += '<br>' + Numberformat(8560);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.0);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.1);//8.560,10
document.body.innerHTML += '<br>' + Numberformat(8560.01);//8.560,01
document.body.innerHTML += '<br>' + Numberformat(8560.009);//8.560,009