Greg Herlihy wrote:

On Mar 17, 9:31 am, Gary Wessle <phd...@yahoo.comwrote:
>Hi

how can I return

0.0002 from 0.00015

and

0.0002 from 0.00014

Example:

double myRound(double myNum, int precision);

myRound(0.00015, 4); //should return 0.0002

myRound(0.00014, 4); //should return 0.0001

myRound(0.00015, 3); //should return 0

myRound(0.00015, 5); //should return 0.00015

Try:

#include <cmath>

using std::pow;

inline

double myRound( double x, int prec)

{

return x * pow(10, prec) * 1.0/pow(10, prec);

}

The idea here is to use exponential expression to compensate for the

imprecise representation of decimal value. Ideally the difference

between the represented value and the true value should "ping-pong"

around 0 - and not steadily move away from 0 in a constant direction.

Did you try?

#include <cmath>

double myRound( double x, int prec ) {

return x * pow(10, prec) * 1.0/pow(10, prec);

}

#include <iostream>

#include <ostream>

#include <iomanip>

int main ( void ) {

double const high = 0.00015;

double const low = 0.00014;

for ( unsigned prec = 1; prec < 10; ++prec ) {

std::cout << prec << " digits. --";

std::cout << std::setprecision(20)

<< myRound( high, prec )

<< ' ';

std::cout << std::setprecision(20)

<< myRound( low, prec )

<< '\n';

}

}

Output on my machine:

1 digits. --0.00014999999999999998686 0.00013999999999999998774

2 digits. --0.00014999999999999998686 0.00013999999999999998774

3 digits. --0.00014999999999999998686 0.00013999999999999998774

4 digits. --0.00014999999999999998686 0.00013999999999999998774

5 digits. --0.00014999999999999998686 0.00013999999999999998774

6 digits. --0.00014999999999999998686 0.00013999999999999998774

7 digits. --0.00014999999999999998686 0.00013999999999999998774

8 digits. --0.00014999999999999998686 0.00013999999999999998774

9 digits. --0.00014999999999999998686 0.00013999999999999998774

To the OP:

Consider rounding at the time of writing the number to some stream.

std::setprecision is your friend.

What is the reason that you want to round intermediate results?

Best

Kai-Uwe Bux