JS精确到指定位数的小数

将数字四舍五入到指定的小数位数。

使用 Math.round() 和模板量将数字四舍五入为指定的小数位数。
省略第二个参数 decimals ,数字将被四舍五入到一个整数。

const NumFun= (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
NumFun(3.1415926, 6)                 // 3.141593
NumFun(3.1415926, 3)                 // 3.142
原创文章 18 获赞 22 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42618523/article/details/102607606