unj2
unj2

Reputation: 53551

How to efficiently calculate double to two decimal precision in C/C++?

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.

Upvotes: 0

Views: 771

Answers (2)

Gangnus
Gangnus

Reputation: 24484

"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.

Upvotes: 0

Torsten Robitzki
Torsten Robitzki

Reputation: 2555

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.

Upvotes: 1

Related Questions