toFixed、Math.round有什么区别?

水一篇,其实也没什么好写的,文档说明也很清晰。。。

1、定义和用法,都是对数字进行四舍五入操作

Math.round()方法,可把一个数字舍入为最接近的整数

toFixed()方法,可把 Number 四舍五入为指定小数位数的数字

 

2、返回值的类型不同

const num = 123;
console.log(typeof(num.toFixed())); // "string"
console.log(typeof(Math.round(num))); // "number"

Math.round()方法,返回值为数字。

toFixed()方法,返回值为字符串。


3、处理精度不同

const num = 100.153;
console.log(num.toFixed(2)); // 100.15
console.log(num.toFixed(1)); // 100.1
console.log(num.toFixed()); // 100

console.log(Math.round(num)); // 100

Math.round()方法,就一个参数,而且用法也说明了,只返回整数。

toFixed()方法,可以接受第二个参数,用来规定小数位数,范围是2-20~

 

parseFloat(((0.1 + 0.2)*10).toFixed(10))

((0.1 + 0.2)*10).toFixed(10) - 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值