toFixed、Math.round 的区别(转载)

转载 https://blog.csdn.net/qq_39571197/article/details/87597062

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

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

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

 

2、返回值的类型不同

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

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

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


3、处理精度不同

  1.  
    const num = 100.153;
  2.  
    console.log(num.toFixed(2)); // 100.15
  3.  
    console.log(num.toFixed(1)); // 100.1
  4.  
    console.log(num.toFixed()); // 100
  5.  
     
  6.  
    console.log(Math.round(num)); // 100

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

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

 

计算时需要 字符串转数字

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

 

Math.round 也可以保留任意位小数
 https://www.cnblogs.com/hao-1234-1234/p/11150134.html
 
 
 
posted @   hao_1234_1234  阅读(517)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示