繁体   English   中英

如何舍入 javascript 中的浮点数?

[英]How to round float numbers in javascript?

例如,我需要将6.6886896.7 ,但它总是显示7

我的方法:

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

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

Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

使用toFixed()函数。

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

更新(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
> +(6.688687).toPrecision(2)
6.7

JavaScript 中的Number对象有一个方法可以满足您的需求。 该方法是Number.toPrecision([precision])

就像.toFixed(1)一样, .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

如果您不仅想在浮动上使用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

更新:

另一种可能的方法是:

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

我的扩展轮函数:

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

见下文

var original = 28.59;

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

希望这是你想要的..

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


舍入到 1 位小数,返回一个浮点数:

 const n = +6.688689.toLocaleString('fullwide', {maximumFractionDigits:1}) console.log( n, typeof 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 位小数,强制显示零:

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


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

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

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

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

例子

roundOff(10.456,2) //output 10.46
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;
}

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

 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

如果你在 node.js 上下文中,你可以尝试mathjs

const math = require('mathjs')
math.round(3.1415926, 2) 
// result: 3.14
+((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
+((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124

我认为以下功能可以提供帮助

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

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

这个答案的小调整:

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
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;
};

前段时间我为四舍五入创建了防弹逻辑。 为什么比别人好? 因为当有很多十进制数字时,它会正确地舍入数字。 它通过将小数位一位一位四舍五入以自然方式完成。

 const roundWithPrecision = (value, precision = 0, cutTrailingZeros = false) => { const roundingBase = Math.pow(10, precision) const number = Math.round((value + Number.EPSILON) * roundingBase) / roundingBase return cutTrailingZeros? number * 1: number } const countDecimalPlaces = (num) => { const text = num?.toString() const index = text?.indexOf('.') return index === -1? 0: (text?.length - index - 1) } const naturalRoundWithPrecision = (number, numberOfDecimalPlaces = 0) => { if (number) { let roundPlaces = countDecimalPlaces(number) if (roundPlaces > 15) { roundPlaces = 15 } if (roundPlaces > 0 && roundPlaces > numberOfDecimalPlaces) { while (roundPlaces >= numberOfDecimalPlaces) { number = roundWithPrecision(number, roundPlaces) roundPlaces-- } } } return number } // Lets round 22863.224999999995 in 2 ways // The proper result is 22863.23, as decimal places ends with the 5. console.log(naturalRoundWithPrecision(22863.224999999995,2) ) console.log(roundWithPrecision(22863.224999999995,2) )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM