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的回答