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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

为了记录在案,如果要舍入的数字和位数足够大,缩放方法理论上可以返回无穷大。在JavaScript中,这应该不是问题,因为最大数字是1.7976931348623157e+308,但如果您使用的是非常大的数字或很多小数位数,您可以尝试使用此函数:

Number.prototype.roundTo=函数(数字){var str=this.toString();var split=this.toString().split('e');var scientific=split.length>1;var指数;if(科学){str=拆分[0];var decimal=str.split('.');如果(小数长度<2)返回此;index=十进制[0]。长度+1+位;}其他的index=Math.floor(this).toString().length+1+位数;if(str.length<=索引)返回此;var数字=str[index+1];var num=Number.parseFloat(str.substring(0,索引));如果(数字>=5){var extra=数学.pow(10,-位);返回此<0?num-额外:num+额外;}if(科学)num+=“e”+拆分[1];返回num;}

其他回答

它可能对你有用,

Math.round(num * 100)/100;

了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。

具有可读选项的函数更直观:

function round_number(options) {
    const places = 10**options.decimal_places;
    const res = Math.round(options.number * places)/places;
    return(res)
}

用法:

round_number({
    number : 0.5555555555555556,
    decimal_places : 3
})

0.556

可以使用.toFixed(小数位数)。

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23

为了记录在案,如果要舍入的数字和位数足够大,缩放方法理论上可以返回无穷大。在JavaScript中,这应该不是问题,因为最大数字是1.7976931348623157e+308,但如果您使用的是非常大的数字或很多小数位数,您可以尝试使用此函数:

Number.prototype.roundTo=函数(数字){var str=this.toString();var split=this.toString().split('e');var scientific=split.length>1;var指数;if(科学){str=拆分[0];var decimal=str.split('.');如果(小数长度<2)返回此;index=十进制[0]。长度+1+位;}其他的index=Math.floor(this).toString().length+1+位数;if(str.length<=索引)返回此;var数字=str[index+1];var num=Number.parseFloat(str.substring(0,索引));如果(数字>=5){var extra=数学.pow(10,-位);返回此<0?num-额外:num+额外;}if(科学)num+=“e”+拆分[1];返回num;}

如果值是文本类型:

parseFloat("123.456").toFixed(2);

如果值是数字:

var numb = 123.23454;
numb = numb.toFixed(2);

有一个缺点,像1.5这样的值将给出“1.50”作为输出。@minitech建议的修复方法:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

Math.round似乎是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:

Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!

toFixed()在某些情况下也不会正确舍入(在Chrome v.55.0.2883.87中测试)!

示例:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

我想,这是因为1.555实际上就像是幕后的浮球1.55499994。

解决方案1是使用具有所需舍入算法的脚本,例如:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

它也在Plunker。

注意:这并不是每个人都能通用的解决方案。有几种不同的舍入算法。您的实现可能不同,这取决于您的需求。请参见舍入。

解决方案2是避免前端计算,并从后端服务器提取舍入值。

另一种可能的解决方案,也不是防弹的。

Math.round((num + Number.EPSILON) * 100) / 100

在某些情况下,当您舍入像1.3549999999999998这样的数字时,它将返回错误的结果。它应该是1.35,但结果是1.36。