我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:

"$ 2,500.00"

我该怎么做?


当前回答

function getMoney(A){
    var a = new Number(A);
    var b = a.toFixed(2); // Get 12345678.90
    a = parseInt(a); // Get 12345678
    b = (b-a).toPrecision(2); // Get 0.90
    b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00
    a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00
    // If Internet Explorer (our number ends in .00)
    if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))
    {
        a = a.substr(0, a.length-3); // Delete the .00
    }
    return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90
}
alert(getMoney(12345678.9));

这适用于Firefox和Internet Explorer。

其他回答

我喜欢VisionN的最短答案,除非我需要修改一个没有小数点的数字(123美元而不是123.00美元)。它不起作用,所以我需要破解JavaScript正则表达式的神秘语法,而不是快速复制/粘贴。

这是最初的解决方案

n.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');

我会再延长一点:

var re = /\d(?=(\d{3})+\.)/g;
var subst = '$&,';
n.toFixed(2).replace(re, subst);

此处的re部分(字符串替换中的搜索部分)表示

查找所有数字(\d)后跟(?=…)(展望)一个或多个组(…)+正好三位数(\d{3})以点(\.)结尾对所有事件执行此操作(g)

这里的子部分是指:

每次有匹配项时,将其替换为自身($&),后跟逗号。

当我们使用string.replace时,字符串中的所有其他文本保持不变,只有找到的数字(后面跟着3、6、9等其他数字的数字)才会得到一个额外的逗号。

因此,在数字1234567.89中,数字1和4满足条件(1234567.89),并被替换为“1”和“4”,从而得到1234567.89。

如果我们根本不需要美元金额的小数点(即123美元而不是123.00美元),我们可以这样更改正则表达式:

var re2 = /\d(?=(\d{3})+$)/g;

它依赖于行尾($)而不是点(\.),最后的表达式将是(请注意Fixed(0)):

n.toFixed(0).replace(/\d(?=(\d{3})+$)/g, '$&,');

此表达式将给出

1234567.89 -> 1,234,567

此外,您也可以选择单词边界(\b),而不是上面正则表达式中的行尾($)。

如果我误解了正则表达式处理的任何部分,我会提前道歉。

这是我的。。。

function thousandCommas(num) {
  num = num.toString().split('.');
  var ints = num[0].split('').reverse();
  for (var out=[],len=ints.length,i=0; i < len; i++) {
    if (i > 0 && (i % 3) === 0) out.push(',');
    out.push(ints[i]);
  }
  out = out.reverse() && out.join('');
  if (num.length === 2) out += '.' + num[1];
  return out;
}

Patrick Desjardins(前Daok)的例子对我很有用。如果有人感兴趣,我将其移植到CoffeeScript。

Number.prototype.toMoney = (decimals = 2, decimal_separator = ".", thousands_separator = ",") ->
    n = this
    c = if isNaN(decimals) then 2 else Math.abs decimals
    sign = if n < 0 then "-" else ""
    i = parseInt(n = Math.abs(n).toFixed(c)) + ''
    j = if (j = i.length) > 3 then j % 3 else 0
    x = if j then i.substr(0, j) + thousands_separator else ''
    y = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_separator)
    z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else ''
    sign + x + y + z

PHP函数“number_format”有一个JavaScript端口。

我发现它非常有用,因为它易于使用,并且对PHP开发人员来说是可识别的。

function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);
    // Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
               _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

(原文注释栏,包括以下示例和到期信用)

// Formats a number with grouped thousands
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/number_format
// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +     bugfix by: Michael White (http://getsprink.com)
// +     bugfix by: Benjamin Lupton
// +     bugfix by: Allan Jensen (http://www.winternet.no)
// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// +     bugfix by: Howard Yeend
// +    revised by: Luke Smith (http://lucassmith.name)
// +     bugfix by: Diogo Resende
// +     bugfix by: Rival
// +     input by: Kheang Hok Chin (http://www.distantia.ca/)
// +     improved by: davook
// +     improved by: Brett Zamir (http://brett-zamir.me)
// +     input by: Jay Klehr
// +     improved by: Brett Zamir (http://brett-zamir.me)
// +     input by: Amir Habibi (http://www.residence-mixte.com/)
// +     bugfix by: Brett Zamir (http://brett-zamir.me)
// *     example 1: number_format(1234.56);
// *     returns 1: '1,235'
// *     example 2: number_format(1234.56, 2, ',', ' ');
// *     returns 2: '1 234,56'
// *     example 3: number_format(1234.5678, 2, '.', '');
// *     returns 3: '1234.57'
// *     example 4: number_format(67, 2, ',', '.');
// *     returns 4: '67,00'
// *     example 5: number_format(1000);
// *     returns 5: '1,000'
// *     example 6: number_format(67.311, 2);
// *     returns 6: '67.31'
// *     example 7: number_format(1000.55, 1);
// *     returns 7: '1,000.6'
// *     example 8: number_format(67000, 5, ',', '.');
// *     returns 8: '67.000,00000'
// *     example 9: number_format(0.9, 0);
// *     returns 9: '1'
// *     example 10: number_format('1.20', 2);
// *     returns 10: '1.20'
// *     example 11: number_format('1.20', 4);
// *     returns 11: '1.2000'
// *     example 12: number_format('1.2000', 3);
// *     returns 12: '1.200'
function getMoney(A){
    var a = new Number(A);
    var b = a.toFixed(2); // Get 12345678.90
    a = parseInt(a); // Get 12345678
    b = (b-a).toPrecision(2); // Get 0.90
    b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00
    a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00
    // If Internet Explorer (our number ends in .00)
    if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))
    {
        a = a.substr(0, a.length-3); // Delete the .00
    }
    return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90
}
alert(getMoney(12345678.9));

这适用于Firefox和Internet Explorer。