fe-interview
fe-interview copied to clipboard
[js] 第679天 如何把10.36四舍五入为最接近的整数?
Math.round(10.36)
Math.round(10.36)==>11 Math.ceil(10.36)==>11 Math.floor(10.36)==>10
+(10.36).toFixed(0),Number.toFixed()按照四舍五入的规则进行取舍
~~(10.36 + .5)
Number((10.36).toFixed(1)).toFixed(0)
✂【回答】 实现“四舍五入”的方法有:
Math.round(x)将数字四舍五入到最接近的整数,如:Math.round(10.36)。NumberObject.toFixed(num)将数字四舍五入为给定的位数,如:(10.36).toFixed(0)。Math.floor(x)将数字下舍入最接近的整数,如:Math.floor(10.36)。parseInt(string, radix)解析字符串并返回整数,如:parseInt(10.36)。Math.trunc(x)返回数字的整数部分,如:Math.trunc(10.36)。~~做两次按位取反的操作,如:~~(10.36)。
🖊【便签】
Math.ceil(x)将数字上舍入最接近的整数,如:Math.ceil(10.36)。(10.36) === Number(10.36) // => true,Number(10.36) === new Number(10.36) // => false。
♡【关注】 https://blog.csdn.net/Hewes
Math.round(10.36) // 结果:10
(10.36).toFixed(0)
const num = 10.36 | 0
// 等同于
const num2 = Math.floor(10.36)
const num = 10.36
console.log(Math.round(num)) // 四舍五入不保留小数
console.log(num.toFixed(0)) // 保留0位小数,并且四舍五入
console.log(num.floor(num)) // 舍弃小数部分
console.log(num.toPrecision(2)) //保留两位有效数字