-1

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.

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
Maxy
  • 21
  • 1

1 Answers1

0

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.

Joundill
  • 6,828
  • 12
  • 36
  • 50
  • What is best way to create month sale growth? using if or switch statements? because you're right about that. – Maxy May 12 '20 at 23:51
  • This is the correct answer by the way. A percentage increase doesn't make sense. If sales increase from $0 to $150, what percentage increase is that? `$0 * 2000% = $0`, `$0 * 15% = $0`. It's up to you to decide how you want to represent an undefined value. – Joundill May 13 '20 at 00:00
  • https://sciencing.com/calculate-percentage-monthly-growth-8124035.html I used this for creating that calculation... – Maxy May 13 '20 at 00:03
  • Because I have sales and users what counts how many purchases and how many users registered. – Maxy May 13 '20 at 00:04
  • That calculation doesn't work if your last month's sales were 0 for the reasons explained in my answer. You should mark the answer as correct :) – Joundill May 13 '20 at 00:07
  • If it doesnt work with 0 maybe explain how it should work. – Maxy May 13 '20 at 00:15
  • It works perfectly with 0. The question `x/0` doesn't make sense, you can't divide a pizza into 0 pieces. Have a read of [this answer](https://matheducators.stackexchange.com/a/5659) on the Maths Educators Stack Exchange. The correct answer is `undefined` or `NaN`. – Joundill May 13 '20 at 00:26
  • asking php function how to do it? – Maxy May 13 '20 at 00:28
  • Your formula is correct, and it is giving you a correct result. Your code doesn't have a problem, you're just dividing by zero. – Joundill May 13 '20 at 00:29
  • Yes but there must be some check point what checks if divider is negative or 0... – Maxy May 13 '20 at 00:42
  • Are you looking for `if($last_month === 0)`? – Joundill May 13 '20 at 00:46