`
bigbone
  • 浏览: 2701 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

將數字每隔三位加上逗號的延伸寫作了

阅读更多
从一个台湾gg拿找到的,感觉挺好用的,谢谢那哥们。
這個程式碎片算是將數字每隔三位加上逗號的延伸寫作了,不過這次重點放在Javascript上的寫法了。如何將12356.25變成金額表示法(NT$12,356.25)呢?程式碼如下:

function money_format(value,fixed,currency){
        var fixed = fixed || 0;
        var currency = currency || '';
        isNaN(parseFloat(value))? value=0 : value=parseFloat(value);
        v = value.toFixed(fixed).toString();
        var ps = v.split('.');
        var whole = ps[0];
        var sub = ps[1] ? '.' + ps[1] : '';
        var r = /(\d+)(\d{3})/;
        while (r.test(whole)) {
                whole = whole.replace(r, '$1' + ',' + '$2');
        }
        v = whole + sub;
        if (v.charAt(0) == '-') {
                return currency + '-' + '$' + v.substr(1);
        }
        return currency + '$' +v;
}
/************
*  測試函式
************/
//使用數字型態或字串型態傳入皆可
money = money_format(-333224);  //輸出$-333,224
money = money_format('-333224');//輸出$-333,224
//指定小數位數
money = money_format(333224,2);    //輸出$333,224.00
money = money_format('333224.2',3);//輸出$333,224.200
//指定幣別
money = money_format(333224,2,'US');//輸出US$333,224.00
money = money_format(333224,0,'NT');//輸出NT$333,224
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics