码迷,mamicode.com
首页 > Web开发 > 详细

js精确到指定位数的小数

时间:2020-06-29 11:47:16      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:keyword   nan   math   ons   nbsp   使用   string   uil   const   

将数字四舍五入到指定的小数位数。使用 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

 

js精确到指定位数的小数

标签:keyword   nan   math   ons   nbsp   使用   string   uil   const   

原文地址:https://www.cnblogs.com/zyz-s/p/13206838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!