JavaScript小数四舍五入的代码

简介: JavaScript小数四舍五入的代码

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

但由于用户使用不同浏览器,并且这些浏览器js库也存在些差异,所以表现也不同,大多数时候是在FF下开发,却忽略了IE等浏览器的兼容问题。
原生toFixed方法555.555.toFixed(2) //输出555.55,IE和FF下执行结果不同
原生toFixed方法555.555.toFixed(2) //输出555.55,IE和FF下执行结果不同
借用网上实现代码:
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
//代码效果参考:http://www.zidongmutanji.com/bxxx/51528.html

//1:先将小数向右移动How位。 //2:将移动后结果四舍五入。 //3:先将小数向左移动How位。 Dight = Math.round (DightMath.pow(10,How))/Math.pow(10,How); return Dight;}console.info(ForDight(12345.67890,2));
另外一种实现方法:
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());
但还是存在问题
555.555.toFixed(2)
555.555.toFixed(2)
输出结果555.55。
比较好的实现方法:
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
//代码效果参考:http://www.zidongmutanji.com/zsjx/293305.html

优化版:
var s = Math.ceil(this 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

相关文章
|
3天前
|
JavaScript 前端开发 Java
java 执行 javascript 代码
java 执行 javascript 代码
15 6
|
2天前
|
前端开发 JavaScript
JavaScript 时空编织者:驾驭代码的控制流程
JavaScript 时空编织者:驾驭代码的控制流程
|
2天前
|
前端开发 JavaScript
JavaScript 魔法秘笈:编织梦幻般的代码艺术王国
JavaScript 魔法秘笈:编织梦幻般的代码艺术王国
|
4天前
|
设计模式 JSON JavaScript
Javascript实现购物车的详细代码
Javascript实现购物车的详细代码
14 3
|
4天前
|
缓存 JavaScript 前端开发
JS代码拆分方法 是对的还是错的?
JS代码拆分方法 是对的还是错的?
10 3
|
4天前
|
JavaScript 数据安全/隐私保护
JS代码是怎样被混淆加密的
JS代码是怎样被混淆加密的
|
4天前
|
Web App开发 人工智能 JavaScript
用 Javascript 代码构建语音助手
用 Javascript 代码构建语音助手
11 2
|
4天前
|
JSON JavaScript 前端开发
Javascript 模块化编程的方法和代码
Javascript 模块化编程的方法和代码
12 1
|
4天前
|
JavaScript 前端开发 算法
JavaScript 中非常实用的单行代码技术
JavaScript 中非常实用的单行代码技术
|
4天前
|
缓存 JavaScript 前端开发
正确拆分JS代码的方法
正确拆分JS代码的方法