使用. tofixed()舍入指数小的数字

round exponentially small number with .toFixed()

本文关键字:数字 指数 舍入 tofixed 使用      更新时间:2023-09-26

如何像这样四舍五入指数小的数字:

2.4451778232910804e-26.toFixed(4) => 2.4452e-26

在docs中,每次使用.toFixed()都会得到0exponentially small number有特殊的功能吗?我宁愿不修改Number.prototype.toFixed()

正如您已经写的,toFixed不够精确,因为它只允许"only"最多20位小数。乘法+除法不能很好地工作,因为除法可能会给你一个不准确的更长的数字。但toPrecision(<amount-of-precision>)可能会有所帮助。

edit:如果你想要4位小数,你需要传递5作为参数(作为点计数前的数字)。

toPrecision将为您提供一个String,但是如果需要,您可以轻松地将其再次转换为数字。例:Number(someNumberAsString)

var someNumber = 2.4451778232910804e-26;
console.log(someNumber);
console.log(someNumber.toPrecision(8));