Home > Back-end >  What is the best condition between negative and positive numbers to avoid repeating comparisons?
What is the best condition between negative and positive numbers to avoid repeating comparisons?

Time:12-17

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?

CodePudding user response:

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))

CodePudding user response:

Make simpler and easier

const decimalFn = ( n ) => {
  let dec;
  n = Math.abs(n)
  if(n <= 999) dec = 0
  if(n <= 99) dec = 1
  if(n <= 9) dec = 2
  if(n <= 1) dec = 3
  return n.toFixed(dec)
}

console.log( decimalFn(-99) )
console.log( decimalFn(-9) )
console.log( decimalFn(-1) )
console.log( decimalFn(0.5) )
console.log( decimalFn(1) )
console.log( decimalFn(9) )
console.log( decimalFn(99) )
console.log( decimalFn(999) )

  • Related