Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中将数字格式化为货币字符串?(How can I format numbers as currency string in JavaScript?)

I would like to format a price in JavaScript. (我想用JavaScript格式化价格。)
I'd like a function which takes a float as an argument and returns a string formatted like this: (我想要一个以float作为参数并返回格式如下的string的函数:)

"$ 2,500.00"

What's the best way to do this? (最好的方法是什么?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Number.prototype.toFixed (Number.prototype.toFixed)

This solution is compatible with every single major browser: (该解决方案与每个主流浏览器兼容:)

  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)

All you need is to add the currency symbol (eg "$" + profits.toFixed(2) ) and you will have your amount in dollars. (您只需要添加货币符号(例如"$" + profits.toFixed(2) ),您便可以用美元表示金额。)

Custom function (自定义功能)

If you require the use of , between each digit, you can use this function: (如果你需要使用的,每个数字之间,您可以使用此功能:)

 function formatMoney(number, decPlaces, decSep, thouSep) { decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces, decSep = typeof decSep === "undefined" ? "." : decSep; thouSep = typeof thouSep === "undefined" ? "," : thouSep; var sign = number < 0 ? "-" : ""; var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces))); var j = (j = i.length) > 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSep : "") + i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) + (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : ""); } document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); }); 
 <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p> 

Use it like so: (像这样使用它:)

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

If you're always going to use '.' (如果您总是要使用'。) and ',', you can leave them off your method call, and the method will default them for you. (和',',您可以将它们保留在方法调用之外,该方法将为您默认它们。)

(123456789.12345).formatMoney(2);

If your culture has the two symbols flipped (ie Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney method: (如果您的文化中有两个翻转的符号(即欧洲符号),并且您想使用默认符号,只需将以下两行粘贴到formatMoney方法中:)

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

Custom function (ES6) (自定义功能(ES6))

If you can use modern ECMAScript syntax (ie through Babel), you can use this simpler function instead: (如果可以使用现代ECMAScript语法(即通过Babel),则可以改用以下更简单的函数:)

 function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") { try { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); } catch (e) { console.log(e) } }; document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); }); 
 <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...