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;
        };
  • 相关阅读:
    MS SQL Server中的CONVERT日期格式化大全
    简历
    Spring源码IOC部分容器简介【1】
    HadoopHDFS设计原理
    1.Linux系统简介
    3.大话C语言变量和数据类型
    2.C语言初探
    7.函数
    8.C语言预处理命令
    9.指针
  • 原文地址:https://www.cnblogs.com/YKSlu/p/12555865.html
Copyright © 2011-2022 走看看