我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

更简单的ES6方法是

const round = (x, n) => 
  Number(parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n));

此模式还返回要求的精度。

ex:

round(44.7826456, 4)  // yields 44.7826
round(78.12, 4)       // yields 78.12

其他回答

这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。

要进行汇总,请使用以下命令:

Math.ceil(num * 100)/100;

这里有一个简单的方法:

Math.round(value * 100) / 100

不过,您可能需要继续创建一个单独的函数来为您执行此操作:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

然后,只需传入值。

通过添加第二个参数,可以将其增强为任意小数位数。

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}

虽然建议的答案通常是正确的,但没有考虑传入的数字的精度,这在原始问题中没有表示为要求,但在科学应用的情况下,这可能是一个要求,其中3不同于3.00(例如)。

事实上,建议的答案是3.001到3,而保持数字精度的信息应该是3.00。

下面是一个考虑到这一点的函数:

函数roundTo(值,十进制){让absValue=Math.abs(值);let int=数学地板(absValue).toString().length;let dec=absValue.toString().length-int;dec-=(Number.isIInteger(absValue)?0 : 1);返回值toPrecision(int+Math.min(dec,十进制));}

请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。

var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));

如果使用的是Lodash库,可以使用Lodash的舍入方法,如下所示。

_.round(number, precision)

例如:

_.round(1.7777777, 2) = 1.78