如何将Javascript中的小数位数圈到1位?你能在小数点后将javascript中的数字舍入为1字符(适当的四舍五入)吗?我试过*10,圆形,/10,但它在整数末尾留下两个小数点。
3 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
Math.round( num * 10) / 10
var number = 12.3456789;var rounded = Math.round( number * 10 ) / 10;// rounded is 12.3
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
round(12345.6789) // 12346
round(12345.6789, -1) // 12350round(12345.6789, -2) // 12300
round(-123.45, 1) // -123.4round(123.45, 1) // 123.5
round(456.7, 2).toFixed(2) // "456.70"
aluckdog
TA贡献1847条经验 获得超7个赞
var number = 123.456;console.log(number.toFixed(1)); // should round to 123.5
添加回答
举报
0/150
提交
取消