我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
请尝试以下代码
"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))
Patrick热门答案的CoffeeScript:
Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->
n = this
c = decimalPlaces
d = decimalChar
t = thousandsChar
c = (if isNaN(c = Math.abs(c)) then 2 else c)
d = (if d is undefined then "." else d)
t = (if t is undefined then "," else t)
s = (if n < 0 then "-" else "")
i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + ""
j = (if (j = i.length) > 3 then j % 3 else 0)
s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "")
数字.原型.固定
此解决方案与每个主要浏览器都兼容:
const profits = 2489.8237;
profits.toFixed(3) // Returns 2489.824 (rounds up)
profits.toFixed(2) // Returns 2489.82
profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)
您只需添加货币符号(例如“$”+利润.toFixed(2)),即可获得美元金额。
自定义函数
如果需要在每个数字之间使用,则可以使用此函数:
函数格式Money(number,decPlaces,decSep,thouSep){decPlaces=isNaN(decPlaces=数学.abs(decPlaces))?2:decPlaces,decSep=decSep的类型==“未定义”?“.”:12月9日;thouSep=thouSep==“未定义”的类型?“,”:thouSep;var符号=数字<0?"-" : "";var i=字符串(parseInt(number=Math.abs(number(number)||0).toFixed(decPlaces)));变量j=(j=i.length)>3?j%3:0;返回标志+(j?i.substr(0,j)+thouSep:“”)+i.substr(j).replace(/(\decSep{3})(?=\decSep)/g,“$1”+thouSep)+(decPlaces?decSep+Math.abs(数字-i).toFixed(decPlace).slice(2):“”);}document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>
这样使用:
(123456789.12345).formatMoney(2, ".", ",");
如果你总是使用“.”和',',您可以将它们从方法调用中删除,方法将为您默认它们。
(123456789.12345).formatMoney(2);
如果您的文化中有两个符号翻转(即,欧洲人),并且您希望使用默认值,只需在formatMoney方法中粘贴以下两行:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
自定义功能(ES6)
如果您可以使用现代ECMAScript语法(即,通过Babel),则可以使用更简单的函数:
函数formatMoney(amount,decimalCount=2,decimal=“.”,千=“,”){尝试{decimalCount=数学.abs(decimalCount);decimalCount=isNaN(decimalCount)?2:小数计数;常量负符号=金额<0?"-" : "";让i=parseInt(amount=Math.abs(Number(amount)||0).toFixed(decimalCount)).toString();设j=(i.length>3)?i.长度%3:0;回来否定符号+(j?i.substr(0,j)+千:“”)+i.substr(j).replace(/(\d{3})(?=\d)/g,“$1”+千)+(decimalCount?decimal+Math.abs(amount-i).toFixed(decimalCount).slice(2):“”);}捕获(e){控制台日志(e)}};document.getElementById(“b”).addEventListener(“单击”,event=>{document.getElementById(“x”).innerText=“结果为:”+formatMoney(document.getElement ById(”d“).value);});<label>插入您的金额:<input id=“d”type=“text”placeholder=“Cash amount”/></label><br/><button id=“b”>获取输出</button><p id=“x”>(按下按钮获取输出)</p>
http://code.google.com/p/javascript-number-formatter/:
短、快、灵活但独立。只有75行,包括MIT许可证信息、空白行和注释。接受标准数字格式,如#、##0.00或带否定的-000.####。接受任何国家/地区格式,如###0,00,#,###.##,#‘###.##或任何类型的非编号符号。接受任意数字分组。#、##、#0.000或#、####0.##均有效。接受任何冗余/防傻瓜格式。##、###、##。#或0#、#00####0#都正常。自动数字舍入。简单的界面,只需提供如下掩码和值:格式(“0.0000”,3.141592)
UPDATE这是我自己开发的应用程序,用于最常见的任务:
var NumUtil = {};
/**
Petty print 'num' wth exactly 'signif' digits.
pp(123.45, 2) == "120"
pp(0.012343, 3) == "0.0123"
pp(1.2, 3) == "1.20"
*/
NumUtil.pp = function(num, signif) {
if (typeof(num) !== "number")
throw 'NumUtil.pp: num is not a number!';
if (isNaN(num))
throw 'NumUtil.pp: num is NaN!';
if (num < 1e-15 || num > 1e15)
return num;
var r = Math.log(num)/Math.LN10;
var dot = Math.floor(r) - (signif-1);
r = r - Math.floor(r) + (signif-1);
r = Math.round(Math.exp(r * Math.LN10)).toString();
if (dot >= 0) {
for (; dot > 0; dot -= 1)
r += "0";
return r;
} else if (-dot >= r.length) {
var p = "0.";
for (; -dot > r.length; dot += 1) {
p += "0";
}
return p+r;
} else {
return r.substring(0, r.length + dot) + "." + r.substring(r.length + dot);
}
}
/** Append leading zeros up to 2 digits. */
NumUtil.align2 = function(v) {
if (v < 10)
return "0"+v;
return ""+v;
}
/** Append leading zeros up to 3 digits. */
NumUtil.align3 = function(v) {
if (v < 10)
return "00"+v;
else if (v < 100)
return "0"+v;
return ""+v;
}
NumUtil.integer = {};
/** Round to integer and group by 3 digits. */
NumUtil.integer.pp = function(num) {
if (typeof(num) !== "number") {
console.log("%s", new Error().stack);
throw 'NumUtil.integer.pp: num is not a number!';
}
if (isNaN(num))
throw 'NumUtil.integer.pp: num is NaN!';
if (num > 1e15)
return num;
if (num < 0)
throw 'Negative num!';
num = Math.round(num);
var group = num % 1000;
var integ = Math.floor(num / 1000);
if (integ === 0) {
return group;
}
num = NumUtil.align3(group);
while (true) {
group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0)
return group + " " + num;
num = NumUtil.align3(group) + " " + num;
}
return num;
}
NumUtil.currency = {};
/** Round to coins and group by 3 digits. */
NumUtil.currency.pp = function(amount) {
if (typeof(amount) !== "number")
throw 'NumUtil.currency.pp: amount is not a number!';
if (isNaN(amount))
throw 'NumUtil.currency.pp: amount is NaN!';
if (amount > 1e15)
return amount;
if (amount < 0)
throw 'Negative amount!';
if (amount < 1e-2)
return 0;
var v = Math.round(amount*100);
var integ = Math.floor(v / 100);
var frac = NumUtil.align2(v % 100);
var group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0) {
return group + "." + frac;
}
amount = NumUtil.align3(group);
while (true) {
group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0)
return group + " " + amount + "." + frac;
amount = NumUtil.align3(group) + " " + amount;
}
return amount;
}
主要部分是插入千个分隔符,可以这样做:
<script type="text/javascript">
function ins1000Sep(val) {
val = val.split(".");
val[0] = val[0].split("").reverse().join("");
val[0] = val[0].replace(/(\d{3})/g, "$1,");
val[0] = val[0].split("").reverse().join("");
val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];
return val.join(".");
}
function rem1000Sep(val) {
return val.replace(/,/g, "");
}
function formatNum(val) {
val = Math.round(val*100)/100;
val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";
var dec = val.indexOf(".");
return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);
}
</script>
<button onclick="alert(ins1000Sep(formatNum(12313231)));">