-5

I have a function here:

  let array = [];
  for (let i = -10; i <= 10; i += 0.1) {
    array.push(i);
  }
  console.log({array});

when i console.log, it returns

0: -10
1: -9.9
2: -9.8
3: -9.700000000000001
4: -9.600000000000001
5: -9.500000000000002
6: -9.400000000000002
7: -9.300000000000002
8: -9.200000000000003
9: -9.100000000000003
10: -9.000000000000004
11: -8.900000000000004
12: -8.800000000000004
13: -8.700000000000005
14: -8.600000000000005
15: -8.500000000000005
...

is there a reason why its not returning whole numbers like -9.7, -9.6 etc? How do I return exact numbers with loop?

2 Answers2

0
    function roundUp(num, precision) {
        precision = Math.pow(10, precision);
        return Math.ceil(num * precision) / precision;
    }
    let array = [];
    for (let i = -10; i <= 10; i += 0.1) {
        roundUp(i, 1);
        array.push(i);
    }
    console.log({array});

I have not tested this but i'm pretty sure it should round it up to 1 decimal point. Hopefully this answers your question or enables you to build your solution

0

For solve the rappresentation, you need to fix number of digits with function toFixed(fractionDigits)

let array = [];
for (let i = -10; i <= 10; i += 0.1) {
    array.push(i.toFixed(1));
}
console.log({array});

There must be no problem with i += 1, infact inside my IDE all work properly (try i = i+1)