js中數字轉金錢格式


參考連接: https://juejin.im/entry/5998f8396fb9a0247c6ec9cd?utm_source=gold_browser_extension

11、如何優雅的實現金錢格式化:1234567890 --> 1,234,567,890

用正則魔法實現:

var test1 = '1234567890' var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format) // 1,234,567,890

非正則的優雅實現:

 function formatCash(str) {
       return str.split('').reverse().reduce((prev, next, index) => { return ((index % 3) ? next : (next + ',')) + prev }) } console.log(formatCash('1234567890')) // 1,234,567,890

其實還有一種很牛逼的方法
number.toLocaleString()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM