Break during a cycle to a negative number

I am trying to break the while loop before it goes into negative numbers, but it keeps going past 0 and showing negative numbers

The problem will be in my while loop, this is the loop

while(Math.round(housetotal)>0){
    housetotal-=o*12;
    zx++;
    row_data.push([zx,
    {v:housetotal, f:'$'+Comma(housetotal)},        
    ]);

    if(zx == year || housetotal<=0){                 
            break
        }

    }

my loop works something like this.

allows

housetotal = 239,852 
o = 1,438

222.596 and continue to count to -1.732 after 14 cycles

im trying to stop it in the 13th cycle, which is 15.524, so it does not go negative

in my while expression, if zx is equal to any number i, which in this case is 15, and o * 12 is any number that increases, multiplied by 12, but in this case is 1,438 x 12 = 17,256

+3
source share
4 answers

One solution is to check the values ​​after the assignment and break the loop:

while(Math.round(housetotal)>0){
   housetotal-=o*12;
   zx++;

   if(zx == year || housetotal<=0)               // moved here
      break;

   row_data.push( [zx, {v:housetotal, f:'$'+Comma(housetotal)}, ]);
}
0

housetotal , . .

, , (1) housetotal, (2) ( row_data.

, , , .

+2
var a = 239.852,
o = 1.432;
while(a>0 && (a-o*12)>0){
    a -= (a-o*12)>0 ? o*12 : 0;
}
0
source

Take a look at the for loop. These are the parts:

<init counter variable>;
while ( <counter condition met> ) {
    <do task>;
    <update counter>;
}

When you update the counter before performing the second task, it will eventually be launched, where the condition is no longer fulfilled. I would suggest for your code:

while( zx != year && Math.round(housetotal) > 0){
    row_data.push([
        zx,
        {v:housetotal, f:'$'+Comma(housetotal)},        
    ]);

    housetotal-=o*12;
    zx++;
}
0
source

All Articles