seyi
seyi

Reputation: 121

Why does this method not give the right multiples of 0.25 in javascript

I am trying to get the multiples of 0.25 but i am getting the wrong output. What am i doing wrong?

let arr1 = []
for (let i = 0.25; i <= 4.25; i++) {
  //console.log(change)
  if (i > 3) {
    continue;
  }
  i % 0.25 == 0 ? arr1.push(i) : 'cancl'
  console.log(arr1) // i get [0.25, 1.25, 2.25] instead of [0.25, 0.5, 0.75, ...]
}

How can i get the write answer/multiples?

Upvotes: 0

Views: 76

Answers (3)

Shivam Gupta
Shivam Gupta

Reputation: 159

The simple flaw in the code is that it is getting incremented by 1.

The condition should be i = i+ .25

Checkout the code below

let arr1 = []
for (let i = 0.25; i <= 4.25; i=i+.25) {
  //console.log(change)
  if (i > 3) {
    continue;
  }
  i % 0.25 == 0 ? arr1.push(i) : 'cancl'
   // i get [0.25, 1.25, 2.25] instead of [0.25, 0.5, 0.75, ...]
}

console.log(arr1)

Upvotes: 1

Tran The Hai
Tran The Hai

Reputation: 1

Because using i++, you will get i + 1 after iterating

Upvotes: -1

Ori Drori
Ori Drori

Reputation: 192222

Your code doesn't work because i++ increments i by 1. Increment i by 0.25 instead:

const arr1 = []
for (let i = .250; i <= 4.25; i += 0.25) {
  arr1.push(i)
}

console.log(arr1)

Upvotes: 2

Related Questions