Get from one number to another number

Tags:



Given a number, say 1.2, is there a simple way in JavaScript, to get to -1.5 in steps of .1. Or from say -50.3 to 12.3.

I’m trying to figure out if there is an easier way of doing this then writing a bunch of complex if statements.

Answer

To avoid accumulating floating point inaccuracies (see Is floating point math broken?) it would be best to multiply your numbers by 10 and then use steps of 1. You can then divide by 10 when generating the results.

Then you just need two for loops: one for counting up, the other for counting down.

function range(start, end) {
  start = Math.round(start * 10);
  end = Math.round(end * 10);
  result = [];
  if (start > end) { // counting down
    for (let i = start; i >= end; i--) {
      result.push(i / 10);
    }
  } else { // counting up
    for (let i = start; i <= end; i++) {
      result.push(i / 10);
    }
  }
  return result;
}

console.log(range(1.2, -1.5));
console.log(range(-50.3, 12.3));


Source: stackoverflow