toFixed()

7 阅读1分钟

toFixed() 是 JavaScript 数字(Number) 的方法,用来把数字按指定的小数位数进行四舍五入并格式化,返回值是 字符串。

const n = 3.14159
n.toFixed(2) // "3.14"
n.toFixed(0) // "3"

重要点

返回的是字符串,不是 number:

const s = (1.2).toFixed(2) // "1.20"

会四舍五入:

(1.005).toFixed(2) // 结果可能是 "1.00"(浮点精度原因,JS 常见坑)

如果你要拿回数字,可以:

Number(n.toFixed(2))