/* * 四舍五入的相关问题 */ /* numObj.toFixed([fractionDigits]) * toFixed 方法返回一个以定点表示法表示的数字的字符串形式。 * 该字符串中小数点之前有一位有效数字,而且其后必须包含 fractionDigits 数字。 * 缺点:保留小数点后fractionDigits位时,fractionDigits之前必须至少有一位>0 */ function do4out var num = new Number("0.105").toFixed(2);//0.11 alert("0.109 == " + num);//0.11 var num = new Number("-1.109").toFixed(2);//-1.11 alert("-1.109 == " + num);//-1.1 var num = new Number("-0.14").toFixed(1);//-0.2 alert("-0.14 == " + num);//0 var num = new Number("0.009").toFixed(2);//0.01 alert("0.009 == " + num);//0.00 //toFixed()转换后为String类型 var num = new Number("9.009").toFixed(2);//9.009 alert(num + 1);//9.011 alert(typeof(num));//string alert(new Number(num) + 1);//10.01 } /* * 解决toFixed四舍五入问题,替换Number.prototype.toFixed 如下 * Math.pow(底数,几次方) * 缺点:但只适用于正数,负数的结果错 */ Number.prototype.toFixed = function(s) { return (parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString(); } /* * 用Math.round()四舍五入,1.5为2,-1.5为-1.5 * 缺点:结果只为整数(即有效位为:小数点后一位),没有小数位,不支持保留小数点有效位 */ function do4out alert("1.5 == " + Math.round(1.5));//2 alert("1.09 == " + Math.round(1.09));//1 alert("-1.5 == " + Math.round(-1.5));//-1.5 alert("-1.8 == " + Math.round(-1.8));//-2 } |
|