码迷,mamicode.com
首页 > 编程语言 > 详细

解决javascript四舍五入不准确

时间:2017-05-31 22:16:22      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:div   length   java   tar   ons   var   net   csdn   style   

 1 function roundFixed(num, fixed) {
 2     var pos = num.toString().indexOf(‘.‘),
 3         decimal_places = num.toString().length - pos - 1,
 4         _int = num * Math.pow(10, decimal_places),
 5         divisor_1 = Math.pow(10, decimal_places - fixed),
 6         divisor_2 = Math.pow(10, fixed);
 7     return Math.round(_int / divisor_1) / divisor_2;
 8 }
 9 
10 console.log(roundFixed(3.135,2));//-> 3.14
11 console.log(roundFixed(2.135,2));//-> 2.14
12 console.log(roundFixed(0.955,1));//-> 1
13 console.log(roundFixed(0.955,2));//-> 0.96
14 console.log(roundFixed(1.955,2));//-> 1.96
15 console.log(roundFixed(1.955,1));//-> 2

参考:http://bbs.csdn.net/topics/391957876  perhapschen的回答

解决javascript四舍五入不准确

标签:div   length   java   tar   ons   var   net   csdn   style   

原文地址:http://www.cnblogs.com/frankwin608/p/6925937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!