JavaScript小数四舍五入toFixed

From: http://kevinpeng.javaeye.com/blog/772591

虽然js中Number对象自带了toFixed方法
Java代码 复制代码
  1. 2.3567.toFixed(2)  
2.3567.toFixed(2)

但由于用户使用不同浏览器,并且这些浏览器js库也存在些差异,所以表现也不同,大多数时候是在FF下开发,却忽略了IE等浏览器的兼容问题。
Java代码 复制代码
  1. 原生toFixed方法555.555.toFixed(2//输出555.55,IE和FF下执行结果不同  
原生toFixed方法555.555.toFixed(2) //输出555.55,IE和FF下执行结果不同

借用网上实现代码:
Java代码 复制代码
  1. function ForDight(Dight,How){   
  2.   //必须是数字或浮点数。如3.56 、 789   
  3.   //1:先将小数向右移动How位。   
  4.   //2:将移动后结果四舍五入。   
  5.   //3:先将小数向左移动How位。   
  6.   Dight = Math.round (Dight*Math.pow(10,How))/Math.pow(10,How);   
  7.   return Dight;   
  8. }   
  9. 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代码 复制代码
  1. Number.prototype.toFixed = function(pos){   
  2.   var p = pos || 2//必须是数字或浮点数,默认精确2位   
  3.   return Math.round(Number(this)*Math.pow(10,p))/Math.pow(10,p);   
  4. }   
  5. 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代码 复制代码
  1. 555.555.toFixed(2)  
555.555.toFixed(2)
输出结果555.55。

比较好的实现方法:
Java代码 复制代码
  1. Number.prototype.toFixed=function(len){   
  2.     var add = 0,s,temp;   
  3.     var s1 = this + "";   
  4.     var start = s1.indexOf(".");   
  5.     //必须是数字或浮点数,判断移动后的前一位是否大于5,大于5加1。   
  6.     if(s1.substr(start+len+1,1)>=5) add=1;   
  7.     var temp = Math.pow(10,len);   
  8.     s = Math.floor(this * temp) + add; // Math.ceil(this * temp)   
  9.     return s/temp;   
  10. }   
  11. 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代码 复制代码
  1. Number.prototype.toFixed=function(len){   
  2.     var temp = Math.pow(10,len);   
  3.     var s = Math.ceil(this * temp)   
  4.     return s/temp;   
  5. }  
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
原文地址:https://www.cnblogs.com/joeblackzqq/p/1902184.html