将小数点四舍五入到前两个有效数字

时间:2018-12-11 16:45:47

标签: javascript ecmascript-6 rounding

我有一种情况,我必须将小数点后四舍五入到前两个有效数字。

示例输入:[0.0000007123123123, 0.0000000012321, 0.0125]

预期输出:[0.00000071, 0.0000000013, 0.013]

2 个答案:

答案 0 :(得分:2)

您可以使用Number.toPrecision https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision

在控制台登录时,我还使用toLocaleString来避免使用e号。

ps。 0.0125通常四舍五入为2个有效数字。0.013

const inputs = [0.0000007123123123, 0.0000000012321, 0.0125];

inputs.forEach(i =>
  console.log(
    Number(i.toPrecision(2)).
      toLocaleString(undefined, {maximumFractionDigits: 20})
  )
);
  

答案 1 :(得分:0)

这是我的解决方案,但我想这可以更简单地完成。

const set = [0.0000007123123123, 0.0000000012321, 0.0125, 1.1005, 0.1511, 1.51231e-10, 10.1505, 1.511e3]

let roundDecimal = (value, precision = 1) => {
    let firstSignificantDigitPlace = e => parseInt(e.toExponential().split('-')[1]) || Math.min(precision, 1)
    if (Array.isArray(value)) {
        return set.map(e => {
            if (typeof e !== 'number') throw "roundDecimal: Array should contains only digits."
            return e.toFixed(firstSignificantDigitPlace(e) + precision )
        })
    } else if (typeof value === 'number') {
        return value.toFixed(firstSignificantDigitPlace(value) + precision )
    }
    throw "roundDecimal: Function accepts only array or digit as value."
}

console.log(roundDecimal(.0051101))
console.log(roundDecimal(set))
console.log(roundDecimal(set, 3))
console.log(roundDecimal(5.153123e-15))
console.log(roundDecimal(Number.NaN))