Reputation: 5853
I have a case, where I have to round decimals to the first two significant digits.
Example input: [0.0000007123123123, 0.0000000012321, 0.0125]
Expected output: [0.00000071, 0.0000000013, 0.013]
Upvotes: 0
Views: 117
Reputation: 5853
This is my solution, but I guess this can be done simpler.
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))
Upvotes: 0
Reputation: 24181
You can use Number.toPrecision
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
I've also used toLocaleString
here to avoid e
numbers when console logging.
ps. 0.0125
normally rounded to 2 significant digits is 0.013
..
const inputs = [0.0000007123123123, 0.0000000012321, 0.0125];
inputs.forEach(i =>
console.log(
Number(i.toPrecision(2)).
toLocaleString(undefined, {maximumFractionDigits: 20})
)
);
Upvotes: 2