且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何在Javascript中舍入到小数点后1位?

更新时间:2023-12-03 16:22:58

Math.round(num * 10)/ 10 有效,这是一个例子......

Math.round( num * 10) / 10 works, here is an example...

var number = 12.3456789;
var rounded = Math.round( number * 10 ) / 10;
// rounded is 12.3

如果你想让它有一个小数位,即使这将是0,然后添加...

if you want it to have one decimal place, even when that would be a 0, then add...

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!



编辑:使用精确函数添加循环...



使用这个原理,作为参考,这是一个方便的小圆函数,需要精确... ...

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;
}

...使用...

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

...默认为舍入到最接近的整数(精度0)...

... defaults to round to nearest whole number (precision 0) ...

round(12345.6789) // 12346

...并且可以使用舍入到最接近的10或100等......

... and can be used to round to nearest 10 or 100 etc...

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

...并且可以与toFixed结合使用格式一致为字符串...

... and can be combined with toFixed to format consistently as string ...

round(456.7, 2).toFixed(2) // "456.70"