I would like to make a bunch of comparisons between numbers, both negative and positive and based on that trim the number `toFixed`

decimal points, but I would like to avoid lengthy conditions. Here’s a code sample:

if ( (numberValue > 100 && numberValue < 999) || (numberValue > -999 && numberValue < -100) ) scalarNotation = numberValue.toFixed(0); else if ( (numberValue > 10 && numberValue < 99) || (numberValue < -10 && numberValue > -99) ) scalarNotation = numberValue.toFixed(1); else if ( (numberValue > 1 && numberValue < 9) || (numberValue < -1 && numberValue > -9) ) scalarNotation = numberValue.toFixed(2); else if ( (numberValue > 0 && numberValue < 1) || (numberValue < 0 && numberValue > -1) ) scalarNotation = numberValue.toFixed(3); else if (numberValue > 1000 || numberValue < -1000) numberValue.toFixed(4);

What is the best way to refactor and perhaps to convert the number to absolute value, add a flag to indicate if the number is positive or negative, and then you can multiply by the modifier at the end?

## Advertisement

## Answer

Here’s one way to simplify the problem.

You can store the checks inside an array of objects, where you specify the limit and the number of decimals. Then, test each one on the absolute value, and return the first match:

function test(num){ const abs = Math.abs(num) const tests = [ {limits: [100, 999], toFixed: 0}, {limits: [10, 99], toFixed: 1}, {limits: [1, 9], toFixed: 2}, {limits: [0, 1], toFixed: 3}, ] let res; tests.forEach(({ limits, toFixed }) => { if(!res && abs > limits[0] && abs < limits[1]) { res = num.toFixed(toFixed) } }) return res || num.toFixed(4) } console.log(test(0.5)) console.log(test(5)) console.log(test(15)) console.log(test(150)) console.log(test(-150)) console.log(test(1500))