tags:

views:

184

answers:

4

Here is my code:

double round( char* strNumber, int decPlace);

int main()
{
    int decimal;
         char initialNumber[256];

    cout << "Enter decimal and number " << endl;

    cin >> decimal;
    cin >> initialNumber;

    cout << setprecision (15) << round ( initialNumber,decimal ) << endl; 

return 0;
}

double round( char* strNumber, int decPlace)//
{
    double number = atof(strNumber);
    int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 );
    double result = ( double ) temp / pow(10.0,decPlace);
    return result;
}

It works up to 6 decimal places. Otherwise it gives some strange result. Below are numbers that I used for testing and the output:

Test 1-round to 7 decimal places

105.265

52.5689745694

25.6835

452.689785

12.456789877458

Output

105.265

52.5689746

25.6835

-214.7483648

12.4567899

Test 1-round to 8 decimal places

The same numbers as previously

Output

-21.47483648

-21.47483648

-21.47483648

-21.47483648

12.45678988
+2  A: 
int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 );

temp is probably 32 bits. It can hold up about +- 2 billion. Overflow.

Richard Pennington
+1  A: 

Looks to me like overflow. pow(10.0,decPlace) * number is a pretty large number - too large to fit in a 32 bit integer (which is what int probably is on your platform).

Adam Wright
+6  A: 

As others have said, the cast to int won't work with large numbers. You could consider using floor instead, and keeping the number to be rounded in a double:

#include <cstdlib>
#include <cmath>

double round( char* strNumber, int decPlace)
{
    double number = std::atof(strNumber);
    double expo = std::pow(10.0,decPlace);
    return std::floor( expo * number + 0.5) / expo;
}
Charles Bailey
This is exactly what I need.
Mike55
@Pat: you should "Accept" the answer then.
jon hanson
+3  A: 

int can hold a smaller range than double; on many platforms its maximum value is about 2 billion, which is less than pow(10.0,8) * number for most of your input numbers.

You could keep your number as a double and use floor to round down to an integer:

double temp = floor( pow(10.0,decPlace) * number + 0.5 );
double result = temp / pow(10.0,decPlace);
Mike Seymour