Skip to content
Advertisement

Growth calculation NaN with 0 value

I try to calculate growth but if I have like last month value zero then it gives me:

‘NaN’

All these values gives me ‘NaN’:

Examples what can be my values:

var_dump((($this_month - $last_month) / $last_month) * 100);
var_dump(((0 - 0) / 0) * 100);
var_dump(((5 - 0) / 0) * 100); //this should be 100% not 'NaN'

Doing something wrong or my math calculation is wrong?

I used this first accepted answer (The percentage increase …):

https://stackoverflow.com/questions/5799055/calculate-percentage-saved-between-two-numbers

I have negative percentages also if last month was successful and current month isnt successful.

Advertisement

Answer

x/0 is undefined, no matter what x is.

If your $last_month == 0, you’re dividing by zero, which mathematically is undefined.

NaN stands for “Not a Number”, i.e. undefined.

The response your code is giving you is correct.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement