蛊毒传说
Math.round( num * 10) / 10工作这里有个例子.。var number = 12.3456789;var rounded = Math.round( number * 10 ) / 10;// rounded is 12.3如果您希望它有一个小数位,即使是0,那么添加.var fixed = rounded.toFixed(1);// fixed is always to 1dp// BUT: returns string!
// to get it back to number formatparseFloat( number.toFixed(2) )// 12.34// but that will not retain any trailing zeros
// so, just make sure it is the last step before output,// and use a number format during calculations!编辑:添加具有精确功能的圆.根据这一原则,这里有一个方便的小圆函数,它需要精度.function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;}..使用.。round(12345.6789, 2) // 12345.68round(12345.6789, 1) // 12345.7..默认值为整到最近的整数(精度0).round(12345.6789) // 12346..可以用来旋转到最近的10或100等等.round(12345.6789, -1) // 12350round(12345.6789, -2) // 12300..正确处理负数.。round(-123.45, 1) // -123.4round(123.45, 1) // 123.5..并且可以与toFixed合并为一致的字符串格式.round(456.7, 2).toFixed(2) // "456.70"