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

我的方法:

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

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


当前回答

我认为这个函数会有帮助。

 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

其他回答

Math.round((6.688689 + Number.EPSILON) * 10) / 10

解决方案被盗自https://stackoverflow.com/a/11832950/2443681

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

一个很好的实用函数来四舍五入所需的十进制精度:

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

还有另一个. tolocalestring()来格式化数字,有很多关于地区、分组、货币格式和符号的选项。一些例子:


四舍五入到小数点后1,返回一个浮点数:

Const n = +6.688689。toLocaleString (fullwide, {maximumFractionDigits: 1}) console.log ( N类型的N )


四舍五入至2位小数,格式为带有指定符号的货币,千位使用逗号分组:

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


格式为区域货币:

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


四舍五入到最小3位小数,强制0显示:

游戏机。log ( 6.000000.toLocaleString(’fullwide’,(minimumFractionDigits: 3)) )


百分比风格的比率。输入* 100,带%符号

游戏机。log ( 6.688689.toLocaleString(' fullwed ') )

乌利希期刊指南(2019 - 10)。感谢Reece Daniels,下面的代码现在可以作为一组函数打包在npm-package expected-round中(看一下)。


你可以使用MDN例子中的辅助函数。你会有更多的灵活性:

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

见下文

原始变量 = 28.59;

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

希望这就是你想要的。

如何正确舍入小数在一个数字(基础): 我们从最右边的数字开始:

如果这个数字>= 5需要四舍五入,那么我们将向左边的第一个数字报告一个1。 如果这个数字< 5表示没有四舍五入

一旦您知道是否需要报告一个值,您就可以删除最后一个数字并重复该操作。

如果有要报告的值,则首先将其添加到最右侧的新数字,然后再重复前面的测试。

注意,有一种特殊情况,当您需要报告一个值,而必须添加到该值的数字是9时:在这种情况下,您必须将数字值更改为0,然后再报告左边接下来的数字为1。

对于一些失败的答案,它看起来像小数被从左到右分割为所需数量的小数,甚至不关心四舍五入。

现在这里声明的是一个函数,它将使用上述逻辑递归地舍入所提供的浮点值。

function roundFloatR(n, precision = 0, opts = { return: 'number' }) { // Use recursivity

    if ( precision == 0 ) { // n will be rounded to the closest integer

        if (opts.return == 'number') return Math.round(n);
        else if (opts.return == 'string') return `${Math.round(n)}`;
    
    } else {

        let ns = `${n}`.split(''); // turns float into a string before splitting it into a char array    

        if ( precision < 0 ) { // precision is a negative number
            precision += ns.length - 1; // precision equals last index of ns - its actual value 

        } else if ( precision > 0 ) { // precision is a positive number
            if ( ns.indexOf('.') > -1 ) 
                precision += ns.indexOf('.'); // precision equals its value + the index of the float separator in the string / array of char
        }

        // RECURSIVE FUNCTION: loop from the end of ns to the precision index while rounding the values
        // index: index in the ns char array, rep: reported value, (INTERNAL_VAR, cn: current number)
        const recursive = (index, rep) => { 
            let cn = parseInt(ns[index]); // get the current number from ns at index

            if (index <= precision) { // current index inferior or equal to the defined precision index (end of rounding) 

                if (rep) { // if a reported value exists
                    cn += rep; // add reported value to current number 

                    if (cn == 10) { // extends rounding for special case of decimals ending with 9 + reported value 
                        ns[index] = '0';
                        recursive( (index - 1), 1 ); // calls recursive() again with a reported value

                    } else if (cn < 10) 
                        ns[index] = `${cn}`;    
                }

            } else if (index > precision) { // current index superior to defined precision index  

                ns.pop(); // each passage in this block will remove the last entry of ns
                if (rep) cn += rep; // adds reported value (if it exists) to current number
                
                if ( cn >= 5 ) // ROUNDING
                    recursive( (index - 1), 1 ); // calls recursive() again with a reported value

                else  // NO ROUNDING
                    recursive( index - 1 ); // calls recursive() again w/o a reported value 
            }  

        }; // end of recursive()

        recursive(ns.length - 1); // starts recursive rounding over the ns char array (arg is the last index of ns)

        if (opts.return == "number") return parseFloat(ns.join('')); // returns float number
        else if (opts.return == "string") return ns.join(''); // returns float number as string
    }

} //

工作原理: 我们首先将提供的float值转换为字符串,然后使用string .split(")指令将其拆分为一个char数组。

然后,我们将以字符数组的最后一个索引作为参数调用递归()函数,在四舍五入值的同时,从最后一个索引遍历该数组到精度索引。

参数说明: 总共有3个参数允许不同的功能。

n: the value to be rounded (number or string). precision: [default = 0] an int which represent the amount of decimals we want to round the provided number to. There are 3 possibilities: precision == 0: value returned will be the same as using the Math.round() method precision > 0: precision will be defined from the float separator index + precision value precision < 0: precision will be defined from the index of the last number - precision value opts: [default = {return: 'number'}] an options object with a unique property called return which take a string value options are 'number' or 'string'. allows the selection of the type of value returned by the function

第2和第3个参数是可选的

用法和示例:

使用浮点值

let n = 20.336099982261654;

let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.34

r = roundFloatR(n, 6); // r = 20.3361
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.336100"

// negative precision
r = roundFloatR(n, -2); // r = 20.3360999822617 

使用字符串值

let n = '20.48490002346038';

let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.49

r = roundFloatR(n, 6); // r = 20.4849
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.484900"

// negative precision
r = roundFloatR(n, -10); // r = 20.4849

性能如何? 大多数情况下,它将在0.3毫秒以内转换提供的值(用performance.now()测量)

不支持的内容和可能出现的问题:

不支持:指数类型值可能需要一些更改来支持它们。 可能的问题: 负精度值超过所提供的数字长度或其浮动分隔符索引可能会导致意想不到的结果,因为这些情况尚未处理。 如果n参数与当前要求的不匹配,则没有错误处理。