I am writing a function to round off numbers based on a given least count.
So for example,
1.2345 with a least count of 0.01 should becoume 1.23
1.23 with a least count of 0.5 should become 1
1.52 with a least count of 0.2 should become 1.4
etc...
Here is my solution, but it feels a bit contrived, could someone please give any suggestions on how to improve it? Follow up, can Regex be used and will that be a more stable implementation?
const round = (num, leastCount) => {
const numDecimals = `${leastCount}`.split('.')?.[1]?.length || 0;
const newNumber = Math.round(num * Math.pow(10, numDecimals) + Number.EPSILON - num * Math.pow(10, numDecimals) % (leastCount * Math.pow(10, numDecimals))) / Math.pow(10, numDecimals)
return newNumber
}
console.log(round(1.2345, 0.01)) // Expected: 1.23
console.log(round(5.66, 1)) // Expected: 5
console.log(round(2.375, 0.005)) // Expected: 2.375
console.log(round(1.33, 0.1)); // Expected: 1.3
console.log(round(2, 0.001)); // Expected: 2
console.log(round(1.7512323, 0.0001)); // Expected: 1.7512
console.log(round(1.52, 0.2)); // Expected: 1.4