本教程提供有关格式化数字的信息,始终显示 2 个小数位并在适用的情况下对它们进行舍入。
我们所需要的只是 JavaScript 内置的 Math.round 方法。
这里有两种方法。
我们可以像这样使用 to.Fixed:
let num = 86.534572; console.log((Math.round(num * 100)/100).toFixed(2));
以下是 2 位小数格式的完整示例:
var num1 = "1"; console.log((Math.round(num1 * 100)/100).toFixed(2)); var num2 = "1.586"; console.log((Math.round(num2 * 100)/100).toFixed(2)); var num3 = "1.756324"; console.log((Math.round(num3 * 100)/100).toFixed(2));
但是,如果值为 1.005,这将失败。
要解决此舍入问题,我们可以使用以指数表示法表示的数字:
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
试试这个例子,看看给定的代码如何解决舍入问题:
console.log(Number(Math.round(1.005 + 'e2') + 'e-2').toFixed(2));
Math.round() 方法
Math.round() 函数将返回四舍五入到最接近整数的数字的值。
如果参数的小数部分大于 0.5,参数将四舍五入为下一个更高的绝对值。
如果参数小于 0.5,它将以较低的绝对值四舍五入。
如果小数部分是 0.5,它将在 +∞ 方向上四舍五入到下一个整数。
日期:2020-06-02 22:16:18 来源:oir作者:oir