W3C定义:toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。(四舍六入五凑偶)

 

实例:

var test = 3.1415926
console.log(test.toFixed(2))

控制台打印

toFixed用法总结-编程之家

在实际使用过程中需要注意的问题

1.返回结果是string类型,如果想对结果有后续的操作计算比较大小等,需要先把结果转换成number类型。

var x = 3.141592
var y = 5.456321
console.log(Number(x.toFixed(2)) < Number(y.toFixed(2))); // true

2.精度问题

当我们需要处理的数据小于零,且需要进位的数字为5时,会发生没进上的情况。

$tofixed (num, n) {var symbol = 1if (num < 0) {// 符号为负symbol = -1num *= -1}var num2 = (Math.round(num * Math.pow(10, n)) / Math.pow(10, n) + Math.pow(10, -(n + 1))).toString().slice(0, -1)return parseFloat(num2 * symbol).toFixed(n)
}

3.如果在项目中使用toFixed方法求得结果有问题,可以尝试下格式化

math.format((this.liveOutput / this.theoryOutput).toFixed(2) * 100, 14)