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

"$ 2,500.00"

我该怎么做?


当前回答

javascript数字格式化程序(以前在Google Code)

短、快、灵活但独立。接受标准数字格式,如#、##0.00或带否定的-000.####。接受任何国家/地区格式,如###0,00,#,###.##,#‘###.##或任何类型的非编号符号。接受任意数字分组。#、##、#0.000或#、####0.##均有效。接受任何冗余/万无一失的格式。##、###、##。#或0#、#00####0#都正常。自动数字舍入。简单的界面,只需提供如下掩码和值:格式(“0.0000”,3.141592)。在掩码中包含前缀和后缀

(摘自自述)

其他回答

这里是XMLilley提供的代码的mootools1.2实现。。。

Number.implement('format', function(decPlaces, thouSeparator, decSeparator){
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
decSeparator = decSeparator === undefined ? '.' : decSeparator;
thouSeparator = thouSeparator === undefined ? ',' : thouSeparator;

var num = this,
    sign = num < 0 ? '-' : '',
    i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + '',
    j = (j = i.length) > 3 ? j % 3 : 0;

return sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : '');
});

数字(值).to固定(2).replace(/(\d)(?=(\d{3})+(?!\d))/g,“$1,”)

请尝试以下代码

"250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');

答案:250000

以下内容简洁易懂,不依赖任何过于复杂的正则表达式。

函数moneyFormat(价格,符号=“$”){const pieces=parseFloat(price).toFixed(2).split(“”)设ii=件长度-3而((ii-=3)>0){拼接件(ii,0,',')}return符号+pieces.join(“”)}控制台日志(money格式(100),money格式(1000),货币格式(10000.00),货币格式(1000000000000000000))

这是一个在最终输出中具有更多选项的版本,允许以不同的位置格式格式化不同的货币。

//高阶函数,接受期权,然后返回价格,并返回格式化的价格常量makeMoneyFormatter=({符号=“$”,分隔符=',',十进制='.',append=false,精度=2,round=真,风俗}={})=>值=>{常量=[1,10,100,1000,10000,100000,1000000,10000000]值=圆形? (数学舍入(值*e[precision])/e[precisity]):parseFloat(值)常量件=值.to固定(精度).replace('.',十进制).split(“”)设ii=工件长度-(精度?精度+1:0)而((ii-=3)>0){件.拼接(ii,0,分隔符)}if(自定义类型==“函数”){返回自定义项({签名float:值,值:pieces.join(“”)})}返回追加? pieces.join(“”)+符号:sign+pieces.join(“”)}//使用正确的格式选项创建货币转换器const formatDollar=makeMoneyFormatter()const formatPound=makeMoneyFormatter({符号:“£”,精度:0})const formatEuro=makeMoneyFormatter({符号:“€”,分隔符:“.”,十进制:',',附加:真})const customFormat=makeMoneyFormatter({圆形:假,custom:({value,float,sign})=>`SALE:$${value}USD`})控制台日志(格式磅(1000),格式美元(10000.0066),格式欧元(1000000.00),自定义格式(999999.555))

String.prototype.toPrice = function () {
    var v;
    if (/^\d+(,\d+)$/.test(this))
        v = this.replace(/,/, '.');
    else if (/^\d+((,\d{3})*(\.\d+)?)?$/.test(this))
        v = this.replace(/,/g, "");
    else if (/^\d+((.\d{3})*(,\d+)?)?$/.test(this))
        v = this.replace(/\./g, "").replace(/,/, ".");
    var x = parseFloat(v).toFixed(2).toString().split("."),
    x1 = x[0],
    x2 = ((x.length == 2) ? "." + x[1] : ".00"),
    exp = /^([0-9]+)(\d{3})/;
    while (exp.test(x1))
        x1 = x1.replace(exp, "$1" + "," + "$2");
    return x1 + x2;
}

alert("123123".toPrice()); //123,123.00
alert("123123,316".toPrice()); //123,123.32
alert("12,312,313.33213".toPrice()); //12,312,313.33
alert("123.312.321,32132".toPrice()); //123,312,321.32