Math.round( num * 10) / 10
works, here is an example...
(Math.round( num * 10) / 10
可以工作,这是一个示例...)
var number = 12.3456789;
var rounded = Math.round( number * 10 ) / 10;
// rounded is 12.3
if you want it to have one decimal place, even when that would be a 0, then add...
(如果您希望它有一个小数位,即使那是0,也可以添加...)
var fixed = rounded.toFixed(1);
// fixed is always to 1dp
// BUT: returns string!
// to get it back to number format
parseFloat( 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!
EDIT: add round with precision function...(编辑:添加具有精度功能的回合...)
Using this principle, for reference, here is a handy little round function that takes precision...
(使用这个原理作为参考,这里有一个方便的小舍入函数,它需要精确...)
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
... usage ...
(...用法...)
round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7
... defaults to round to nearest whole number (precision 0) ...
(...默认舍入到最接近的整数(精度0)...)
round(12345.6789) // 12346
... and can be used to round to nearest 10 or 100 etc...
(...并可以四舍五入到最接近的10或100等...)
round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300
... and correct handling of negative numbers ...
(...以及正确处理负数...)
round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5
... and can be combined with toFixed to format consistently as string ...
(...并且可以与toFixed组合以一致地格式化为字符串...)
round(456.7, 2).toFixed(2) // "456.70"