6
\$\begingroup\$
public double getValueWithPercentage(double number, double percentage)
{
    return number + ((percentage / 100.0) * number);
}

Are there any tricks to optimize this simple code?

\$\endgroup\$

migrated from stackoverflow.com Jan 12 '12 at 4:41

This question came from our site for professional and enthusiast programmers.

  • 5
    \$\begingroup\$ What lead you to believe that this method may need optimising? \$\endgroup\$ – Tim Cooper Jan 11 '12 at 23:49
  • 1
    \$\begingroup\$ are you talking about performance optimization, or precision increase? which are the variable ranges? \$\endgroup\$ – djjeck Jan 11 '12 at 23:53
  • \$\begingroup\$ I think it's worth noting a few things. 1. Multiplication is faster than division. 2. Bitshifting, or Bitwise operations, will not be faster since most compilers perform this for you 3. Unless you are working with VERY large numbers, aka BigInteger, you won't see improvements with multiplication algorithms like Schönhage–Strassen. \$\endgroup\$ – Tony R Jan 12 '12 at 20:27
11
\$\begingroup\$

Since floating-point divide is sometimes a little slower than multiply (and never faster, AFAIK), I'd write your function like this:

public double getValueWithPercentage(double number, double percentage)
{
    return number * (1 + percentage * 0.01);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy