zoukankan      html  css  js  c++  java
  • 关于浏览器Number.toFixed的错误修复

    问题描述如下:

       var n = 1.255;
         var fixed = n.toFixed(2);
         console.log(fixed);//结果:1.25
     
     /*
     以上代码运行预期的结果是1.26,但是得到的结果却是1.25,为什么会出现这个情况?我们要的浮点数为何出现错误;
     然而我们可以再测试:
    
    console.log(1.255*100);这行代码并不等于125.5,而是等于  125.49999999999999
    
    也就可以完全肯定,这既是一个计算机精度错误导致的
    
    那么我们又该如何去消除这个Number类型下的四舍五入精度误差呢?以下为我个人使用方法
    */
    
    
        Number.prototype.toFixed = function(n) {
          n = Math.round(n); //防传入小数
    
          const pow = Math.pow(10, n);
          const num = Math.fround(this * pow);
          const result = (Math.round(num) / pow).toString();
    
          let [int, float] = result.split(".");
    
          float = float || "";
    
          let floatLen = float ? float.length : 0;
          let fillLen = n - floatLen;
    
          if (fillLen <= n) {
            for (let i = 0; i < fillLen; i++) {
              float += "0";
            }
          }
    
          return n === 0 ? int : int + "." + float;
        };
  • 相关阅读:
    [CF1051F] The Shortest Statement
    [国家集训队] 墨墨的等式
    [CF558E] A Simple Task
    [洛谷P1349] 广义斐波那契数列
    [TJOI2009] 猜数字
    [洛谷P3403] 跳楼机
    学习力
    启动流程
    《鸟哥Linux》笔记——磁盘分区
    indexDB数据库
  • 原文地址:https://www.cnblogs.com/YKSlu/p/12555865.html
Copyright © 2011-2022 走看看