0

Given two doubles I need to calculate the percentage and express them to upto 2 decimal places. What is the most efficient way to do so?

For example

x = 10.2476
y = 100

I would return 10.25.

Efficient as in runtime speed. It needs to express x/y*100 in 2 decimal places.

unj2
  • 52,135
  • 87
  • 247
  • 375
  • What's wrong with how you're already doing it? – Ignacio Vazquez-Abrams Feb 21 '14 at 04:39
  • 1
    The answer in [round() for float in C++](http://stackoverflow.com/questions/485525/round-for-float-in-c) might be useful. – R Sahu Feb 21 '14 at 04:52
  • 2
    R Sahu's link's excellent... you can multiply by 100, round, divide by 100. Note that you still might get surprises... something you think should be 2.005 might actually be stored as 2.00499999997 or whatever, getting rounded down yielding 2.00 instead of up to 2.01. That's life with base-2 floating point - no perfect solution. – Tony Delroy Feb 21 '14 at 04:59
  • 2
    Efficient in what sense? Ease/clarity of coding, Runtime speed, code size? What is the significance of y here? Is it expressing the two decimal places? The percentage difference between x and y in this case is not 10.25. Is it the percentage x is of y? – sj0h Feb 21 '14 at 05:10
  • By 'express' do you mean 'output' or 'hold in a variable', because if you want to output to 2dp then that is a different answer to calculating a decimal value. – Pete Kirkham Feb 21 '14 at 12:31

2 Answers2

1

Use an integer representation, if you really need a fixed point representation and scale your numbers by 100. So x = 10.2476 becomes xi = 1025:

double x = 10.2476;
int xi   = ( x + 0.005 ) * 100;

In many cases, floating point representation are not needed, even when numbers smaller than 1 are used.

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35
0

"express them to upto 2 decimal places" means you have only 2 mantissa digits in the output.

10.2476-> 10
102.476 -> 1.0E+2,  NOT 100!
0.00102476 -> 1.0E-3 

So, working with mantissa, it is impossible to show the result not using floats or doubles.

In printf, the keys g and G set the number of significant digits. %2g - exactly 2 decimal places.

As for counting, the decimal division is not a problem operation (as + or -). So, simply divide them, multiply by 100, to show in percents - no problems.

Gangnus
  • 24,044
  • 16
  • 90
  • 149