Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break while loop before negative number

Tags:

javascript

Im trying to break a while loop before it goes into the negative numbers but it keeps going past 0 and showing a negative numbers

The problem would be 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.

lets say

housetotal = 239,852 
o = 1,438

222,596 and continue to count down to -1,732 after 14 loops

im trying to make it stop at the 13th loop which is 15,524 so it doesn't go into the negative

in my while statement i have if zx which is equal to whatever number i have which in this case is 15 and o*12 is whatever number that comes up multiplied by 12 but in this case is 1,438 x 12 = 17,256

like image 667
Suzed Avatar asked Aug 12 '26 08:08

Suzed


1 Answers

You are requiring housetotal to be positive after rounding at the very start of each loop iteration, and breaking out of the loop if it's not positive at the very end of each loop iteration. So far, so good.

But then, after those checks, you (1) change the value of housetotal and then (2) make use of it (in this case, putting it into row_data.

If you want to make sure that the value is positive when it's used, you should test it immediately before it's used.

like image 137
Gareth McCaughan Avatar answered Aug 15 '26 08:08

Gareth McCaughan