js精确到指定位数的小数

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

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)

round(3.1415926535897932384626433832, 2)      // 3.14

round(3.1415926535897932384626433832, 19)     // 3.141592653589793

round(3.1415926535897932384626433832, 20)     // 3.141592653589793

round(3.1415926535897932384626433832, 21)      // NaN

注意:第21位就为NaN

 
posted @ 2020-06-29 11:05  清风引佩下瑶台  阅读(798)  评论(0编辑  收藏  举报