From: http://kevinpeng.javaeye.com/blog/772591
雖然js中Number對象內建了toFixed方法
Java代碼
- 2.3567.toFixed(2)
2.3567.toFixed(2)
但由於使用者使用不同瀏覽器,並且這些瀏覽器js庫也存在些差異,所以表現也不同,大多數時候是在FF下開發,卻忽略了IE等瀏覽器的相容問題。 Java代碼
- 原生toFixed方法555.555.toFixed(2) //輸出555.55,IE和FF下執行結果不同
原生toFixed方法555.555.toFixed(2) //輸出555.55,IE和FF下執行結果不同
借用網上實現代碼: Java代碼
- function ForDight(Dight,How){
- //必須是數字或浮點數。如3.56 、 789
- //1:先將小數向右移動How位。
- //2:將移動後結果四捨五入。
- //3:先將小數向左移動How位。
- Dight = Math.round (Dight*Math.pow(10,How))/Math.pow(10,How);
- return Dight;
- }
- console.info(ForDight(12345.67890,2));
function ForDight(Dight,How){ //必須是數字或浮點數。如3.56 、 789 //1:先將小數向右移動How位。 //2:將移動後結果四捨五入。 //3:先將小數向左移動How位。 Dight = Math.round (Dight*Math.pow(10,How))/Math.pow(10,How); return Dight;}console.info(ForDight(12345.67890,2));
另外一種實現方法: Java代碼
- Number.prototype.toFixed = function(pos){
- var p = pos || 2; //必須是數字或浮點數,預設精確2位
- return Math.round(Number(this)*Math.pow(10,p))/Math.pow(10,p);
- }
- console.info((12345.67890).toFixed());
Number.prototype.toFixed = function(pos){ var p = pos || 2; //必須是數字或浮點數,預設精確2位 return Math.round(Number(this)*Math.pow(10,p))/Math.pow(10,p);}console.info((12345.67890).toFixed());
但還是存在問題
Java代碼
- 555.555.toFixed(2)
555.555.toFixed(2)
輸出結果555.55。
比較好的實現方法: Java代碼
- Number.prototype.toFixed=function(len){
- var add = 0,s,temp;
- var s1 = this + "";
- var start = s1.indexOf(".");
- //必須是數字或浮點數,判斷移動後的前一位是否大於5,大於5加1。
- if(s1.substr(start+len+1,1)>=5) add=1;
- var temp = Math.pow(10,len);
- s = Math.floor(this * temp) + add; // Math.ceil(this * temp)
- return s/temp;
- }
- 555.555.toFixed(2) //輸出555.56
Number.prototype.toFixed=function(len){ var add = 0,s,temp; var s1 = this + ""; var start = s1.indexOf("."); //必須是數字或浮點數,判斷移動後的前一位是否大於5,大於5加1。 if(s1.substr(start+len+1,1)>=5) add=1; var temp = Math.pow(10,len); s = Math.floor(this * temp) + add; // Math.ceil(this * temp) return s/temp;}555.555.toFixed(2) //輸出555.56
最佳化版: Java代碼
- Number.prototype.toFixed=function(len){
- var temp = Math.pow(10,len);
- var s = Math.ceil(this * temp)
- return s/temp;
- }
Number.prototype.toFixed=function(len){ var temp = Math.pow(10,len); var s = Math.ceil(this * temp) return s/temp;}
555.555.toFixed(2) //輸出555.56