Home javascript Find a percentage difference between 2 numbers

Find a percentage difference between 2 numbers

Author

Date

Category

There is a formula:

100 * (y-x) / x

Yes, it calculates like norms, for example x = 10, y = 20 shows a difference of 100% all Hood. But take for example x = 10 000 000 y = 100, it shows -100% – it doesn’t look like the truth, minus should be clearly less than -100 . There is still a condition that any number can be both positive and negative.
Example on Fiddle


Answer 1, Authority 100%

As already mentioned earlier in the comments, if you consider how much mentally differs from Y, then your formula is true and gives the correct answer.
For example, would you have 2 numbers: x = 10 and y = 0 , then x would be distinguished from y 100%, and your example can be brought to such See: x = 10 and y = 0.0001 , which is almost 100% (you also, because of integer arithmetic issues 100% , so to get an answer in the form of a floating point number, or use the multiplication advice on double (on 100. , for example), or continue to read in integers if You need an integer answer).
Now, if you thought how much y greatly differs from x, then the answer would be really different 100.0 * (10 000 000 - 100) / 100.0 == 9 999 900% (i.e. 100.0 * (X - Y) / Y ), i.e. If you need to consider relative to the smallest number (for how many percent is the smallest number from the largest), then simply change the formula arguments in places (substitute it instead of x the smallest number, and instead of y The greatest).

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions