日期:2011/11/10 來源:GBin1.com javascript
Javascript沒有任何內建的格式化函數,這裏咱們經過Google收集了5個javascript的數字格式化函數,但願對於你們的web開發可以帶來方便。html
這兩段代碼幫助你作到四捨五入,對於你顯示價格或者訂單比較有用:java
代碼1: web
function CurrencyFormatted(amount) { var i = parseFloat(amount); if(isNaN(i)) { i = 0.00; } var minus = ''; if(i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if(s.indexOf('.') < 0) { s += '.00'; } if(s.indexOf('.') == (s.length - 2)) { s += '0'; } s = minus + s; return s; } /** * Usage: CurrencyFormatted(12345.678); * result: 12345.68 **/
代碼2:函數
function format_number(pnumber,decimals){ if (isNaN(pnumber)) { return 0}; if (pnumber=='') { return 0}; var snum = new String(pnumber); var sec = snum.split('.'); var whole = parseFloat(sec[0]); var result = ''; if(sec.length > 1){ var dec = new String(sec[1]); dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals))); dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals)); var dot = dec.indexOf('.'); if(dot == -1){ dec += '.'; dot = dec.indexOf('.'); } while(dec.length <= dot + decimals) { dec += '0'; } result = dec; } else{ var dot; var dec = new String(whole); dec += '.'; dot = dec.indexOf('.'); while(dec.length <= dot + decimals) { dec += '0'; } result = dec; } return result; } /** * Usage: format_number(12345.678, 2); * result: 12345.68 **/
原文來自:分享5個javascript的數字格式化函數 code