JavaScript小数四舍五入toFixed

本文介绍了JavaScript中toFixed方法的不同实现方式及其存在的问题。通过几种不同的方法解决了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/archive/2010/12/10/1902184.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值