0

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.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
Scott Paterson
  • 141
  • 3
  • 13

2 Answers2

2

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));
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

for (let number = -10.5; number < 10.5; number += 0.1) {
    realPart = number - (number - Math.floor(number));
    decimalPart = Math.floor((number - Math.floor(number)) * 10) / 10;
    console.log( realPart + decimalPart);
}

// or

for (let number = 10.5; number > -10.5; number -= 0.1) {
    realPart = number - (number - Math.floor(number));
    decimalPart = Math.floor((number - Math.floor(number)) * 10) / 10;
    console.log( realPart + decimalPart);
}
Osman Durdag
  • 955
  • 1
  • 7
  • 18