【问题标题】:How to round float numbers in javascript?如何在javascript中舍入浮点数?
【发布时间】:2012-03-16 05:47:35
【问题描述】:

例如,我需要将6.688689 舍入为6.7,但它总是显示7。

我的方法:

Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or 
Math.round(6.688689, 2);

但是结果总是一样的7...我做错了什么?

【问题讨论】:

标签: javascript rounding


【解决方案1】:
Number((6.688689).toFixed(1)); // 6.7

【讨论】:

  • 将数字转换为字符串然后再转换回来?这不可能很快。
  • 如果您的数字的小数位数少于所需,则不好。它增加了一些
  • 作为 JS 基准测试显示,它比@fivedigit 方法慢
  • Number((456.1235).toFixed(3)) -> 456.123, Number((1.235).toFixed(2)) -> 1.24... 愚蠢的 JavaSript...
  • 这可能不会达到您的预期!结果甚至可能取决于浏览器,请参阅此问题:stackoverflow.com/q/566564/2224996
【解决方案2】:
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

【讨论】:

  • 这并不总是有效。以Math.round(1.005*100)/100 为例,来自MDN
  • @tybro0103 浮点邪恶:1.005 * 100 = 100.49999999999999(至少在我尝试过的 JS 引擎中)。这就是为什么它不起作用以及为什么你永远不应该依赖浮点数完全准确的原因。
  • 错了。 Math.round(1.015 * 100) / 100 返回 1.01 而不是 1.02
  • @MarcoMarsala 错误。谁说 0.5 等于 1?没有 100% 正确的约定,任何一个变体都是正确的。
【解决方案3】:

使用toFixed()函数。

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

【讨论】:

  • 这可能不会达到您的预期!结果甚至可能取决于浏览器,请参阅此问题:stackoverflow.com/q/566564/2224996
  • (6.688689).toFixed();等于“7”而不是 7。其他示例相同。
  • 这个答案具有误导性。例如(1).toFixed(4) 返回 '1.0000'
【解决方案4】:

更新(2019-10)。感谢Reece Daniels 下面的代码现在可以作为一组函数打包在 npm-package expected-round 中(看看)。


您可以使用来自MDN example 的辅助函数。比你有更多的灵活性:

Math.round10(5.25, 0);  // 5
Math.round10(5.25, -1); // 5.3
Math.round10(5.25, -2); // 5.25
Math.round10(5, 0);     // 5
Math.round10(5, -1);    // 5
Math.round10(5, -2);    // 5

更新 (2019-01-15)。似乎 MDN 文档不再有这个帮助函数。这是带有示例的备份:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

用法示例:

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

【讨论】:

  • ?? “Math.round10 不是函数”
  • 我发现这非常有用,所以将它放在一个快速的 npm 包中,供那些希望在不增加额外代码的情况下使用它的人使用。也将原始答案归功于@a.s.panchenko:npmjs.com/package/expected-round
【解决方案5】:
> +(6.688687).toPrecision(2)
6.7

JavaScript 中的Number 对象有一个方法可以完全满足您的需求。 That method is Number.toPrecision([precision]).

就像.toFixed(1) 一样,它将结果转换为字符串,并且需要将其转换回数字。在这里使用+ 前缀完成。

我的笔记本电脑上的简单基准测试:

number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms

【讨论】:

  • 在我看来这是最好的答案(就最佳实践而言最好,最直接的方法)。
  • 1e-10.toPrecision(3): "1.00e-10" - 四舍五入到有效数字。
  • 当心,正如@VsevolodGolovanov 所说,它是有效数字,而不是小数。例如,考虑1234.5678:toFixed(6) =&gt; "1234.567800"、toFixed(2) =&gt; "1234.57"、toPrecision(6) =&gt; "1234.57" 和 toPrecision(2) =&gt; "1.2e+3"。
  • 每个范围都不同,但在 my 范围内,这对我有帮助 =) 谢谢
【解决方案6】:

如果您不仅想在浮点数上使用toFixed(),还想使用ceil() 和floor(),那么您可以使用以下函数:

function roundUsing(func, number, prec) {
    var tempnumber = number * Math.pow(10, prec);
    tempnumber = func(tempnumber);
    return tempnumber / Math.pow(10, prec);
}

生产:

> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112

UPD:

另一种可能的方法是:

Number.prototype.roundUsing = function(func, prec){
    var temp = this * Math.pow(10, prec)
    temp = func(temp);
    return temp / Math.pow(10, prec)
}

生产:

> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6

【讨论】:

  • 我们如何决定何时使用 ceil、floor 或 round 进行舍入?例如:roundUsing(Math.round, 1.015, 2) roundUsing(Math.ceil, 1.015, 2) 给出 2 个不同的值我们如何知道使用哪一个
  • @gaurav5430,这完全取决于业务逻辑。您应该知道是否需要始终向上、向下、到最接近的值或其他值。
【解决方案7】:

我的扩展轮函数:

function round(value, precision) {
  if (Number.isInteger(precision)) {
    var shift = Math.pow(10, precision);
    // Limited preventing decimal issue
    return (Math.round( value * shift + 0.00000000000001 ) / shift);
  } else {
    return Math.round(value);
  }
} 

示例输出:

round(123.688689)     // 123
round(123.688689, 0)  // 123
round(123.688689, 1)  // 123.7
round(123.688689, 2)  // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02

【讨论】:

  • 这类似于@fivedigit 的回答。 round(1.015, 2) 仍然给出 1.01 而不是 1.02
【解决方案8】:

见下文

var original = 28.59;

var result=Math.round(original*10)/10 将返回您返回 28.6

希望这是你想要的..

【讨论】:

  • “如果我每次看到有人使用 FLOAT 存储货币时都能得到一角钱,我会得到 999.997634 美元”——Bill Karwin。
  • 错了。 Math.round(1.015 * 100) / 100
【解决方案9】:

还有.toLocaleString() 来格式化数字的替代方法,有很多关于语言环境、分组、货币格式、符号的选项。一些例子:


四舍五入,返回浮点数:

const n = +6.688689.toLocaleString('fullwide', {maximumFractionDigits:1})
console.log(
  n, typeof n
)

四舍五入到2位小数,格式为currency指定符号,千位使用逗号分组:

console.log(
  68766.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'currency', currency:'USD', useGrouping:true})   
)

格式为locale货币:

console.log(
  68766.688689.toLocaleString('fr-FR', {maximumFractionDigits:2, style:'currency', currency:'EUR'})   
)

四舍五入到小数点后 3 位,强制显示零:

console.log(
  6.000000.toLocaleString('fullwide', {minimumFractionDigits:3})
)

比率的百分比样式。输入 * 100 带 % 符号

console.log(
  6.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'})
)

【讨论】:

    【解决方案10】:

    如果 toFixed() 不起作用,我有很好的解决方案。

    function roundOff(value, decimals) {
      return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
    }
    

    例子

    roundOff(10.456,2) //output 10.46
    

    【讨论】:

      【解决方案11】:
      float(value,ndec);
      function float(num,x){
      this.num=num;
      this.x=x;
      var p=Math.pow(10,this.x);
      return (Math.round((this.num).toFixed(this.x)*p))/p;
      }
      

      【讨论】:

        【解决方案12】:

        我认为这个功能可以提供帮助。

         function round(value, ndec){
            var n = 10;
            for(var i = 1; i < ndec; i++){
                n *=10;
            }
        
            if(!ndec || ndec <= 0)
                return Math.round(value);
            else
                return Math.round(value * n) / n;
        }
        
        
        round(2.245, 2) //2.25
        round(2.245, 0) //2
        

        【讨论】:

        • 类似于其他一些答案,这对于 round(1.015, 2) 失败,应该给出 1.02
        【解决方案13】:

        如果你在 node.js 环境下,你可以试试mathjs

        const math = require('mathjs')
        math.round(3.1415926, 2) 
        // result: 3.14
        

        【讨论】:

          【解决方案14】:
          +((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
          +((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124
          

          【讨论】:

          【解决方案15】:
          Math.round((6.688689 + Number.EPSILON) * 10) / 10
          

          从https://stackoverflow.com/a/11832950/2443681窃取的解决方案

          这应该适用于几乎任何浮点值。但它不强制十进制计数。目前尚不清楚这是否是一项要求。应该比使用 toFixed() 更快,根据其他答案的 cmets 也有其他问题。

          一个很好的实用函数,用于以所需的小数精度进行舍入:

          const roundToPrecision = (value, decimals) => {
            const pow = Math.pow(10, decimals);
            return Math.round((value + Number.EPSILON) * pow) / pow;
          };
          

          【讨论】:

            【解决方案16】:

            我认为下面的函数可以提供帮助

            function roundOff(value,round) {
               return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
            }
            

            用法:roundOff(600.23458,2); 将返回 600.23

            【讨论】:

            • 您能解释一下这个答案增加了哪些之前的答案尚未涵盖的内容吗?
            • 类似于其他一些答案,这对于 round(1.015, 2) 失败,应该给出 1.02
            【解决方案17】:

            对this answer的小调整:

            function roundToStep(value, stepParam) {
               var step = stepParam || 1.0;
               var inv = 1.0 / step;
               return Math.round(value * inv) / inv;
            }
            
            roundToStep(2.55, 0.1) = 2.6
            roundToStep(2.55, 0.01) = 2.55
            roundToStep(2, 0.01) = 2
            

            【讨论】:

            • roundToStep(1.015, 0.002) 给出 1.014 。这是正确的使用方法吗
            • @gaurav5430 试试roundToStep(1.015, 0.001)
            【解决方案18】:

            如果您今天使用 Browserify,您将不得不尝试:roundTo 一个非常有用的 NPM 库

            【讨论】:

              猜你喜欢
              • 2018-08-13
              • 1970-01-01
              • 2016-12-28
              • 2015-09-07
              • 2022-12-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-06-09
              相关资源
              最近更新 更多