Solved

Posted on 2011-10-27

I want a function that returns the the % differnece between two numbers.

I got the formula from this website:

http://www.ehow.co.uk/how_6331196_calculate-percent-difference.html

This is my function:

Please can someine tell me if this is ok?? Is there a better way to do this??

I got the formula from this website:

http://www.ehow.co.uk/how_

This is my function:

```
int MyClass::CalculatePercentageDifference( uint64_t firstNumber, uint64_t secondNumber ) const
{
if( secondNumber == 0 || firstNumber == 0 )
return -1;
double percentDiff = ((((double)secondNumber - (double)firstNumber) / (double)firstNumber) * 100);
return (int)percentDiff;
}
```

Please can someine tell me if this is ok?? Is there a better way to do this??

12 Comments

return -1;

shouldnt this return 100 as the percentage is of 100% difference

is one kind of percentage difference

(secondNumber - firstNumber)*100.0/secondN

is another

(secondNumber - firstNumber)*200.0/(firstN

is a more symmetric kind of difference

abs(secondNumber - firstNumber)*100.0/max(abs

may be an appropriate kind of percentage difference in other cases

What is the application of this function?

This function will accept a number and return that same number increased or decreased by a certain percentage.

re: shouldnt this return 100 as the percentage is of 100% difference.

If any of the numbers are 0 I want to ignore the result.

This function will accept a number and return that same number increased or decreased by a certain percentage.That sounds like the opposite of what CalculatePercentageDiffere

What you describe sounds like it would take firstNumber and percentDiff as parameters and return secondNumber as a result.

If any of the numbers are 0 I want to ignore the result.does that mean that

CalculatePercentageDiffere

CalculatePercentageDiffere

CalculatePercentageDiffere

are all considered equivalent?

If you have two numbers - 95 and 100 - 95 is 5 percent less than 100 - but 100 is not 5 percent greater than 95. It is 5.263 percent greater.

Consider the following two where n is any integer number

CalculatePercentageDiffere

CalculatePercentageDiffere

the return of both of these is -1.

Now consider eg.

CalculatePercentageDiffere

The return value is -1.

The webpage you have as reference indicates that you followed almost the right way...

One small addition in case of dividing by zero error or other errors:

1. As the webpage says the difference will be good to report a double value...

2. In case of error it will be better to have a boolean return value.

bool MyClass::CalculatePercenta

{

if( secondNumber == 0 || firstNumber == 0 )

return false;

diff = ((((double)secondNumber - (double)firstNumber) / (double)firstNumber) * 100);

return true;

}

George Tokas.

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**16** Experts available now in Live!