Developer Notes

JavaScript: Number rounding

July 21, 2021

So to be able to round a number in JavaScript I found that this is the best and easy way. This way I don’t have to convert the Number to String to cut some digits and the transform it back to Number

1/**
2 * @param value - number - Number to round
3 * @param decimals - number - how many digits after the `.`
4 * @return number
5 */
6function round(value, decimals) {
7 return Number(Math.round(`${value}e${decimals}`) + 'e-' + decimals);
8}

To prove it, here is a test for it

1describe('Number rounding', () => {
2 it('should return expected value', () => {
3 [
4 [2.1234, 2.12, 2],
5 [2.125, 2.13, 2],
6 [2.11111, 2.11, 2],
7 [2.11115, 2.1112, 4],
8 [2.123, 2, 0],
9 [2.123, NaN, 0],
10 ["2.123", 2.12, 2]
11 ].forEach(([value, expectedValue, decimals]) => {
12 expect(round(value, decimals)).toBe(expectedValue)
13 })
14 })
15})

My name is Bozhidar Dryanovski and I'm a Software Engineer at Clarity
You should follow me on Twitter or Check my work at Github

© 2021, Build version 2.0.5