Explicitly rounding numbers to more than 7 decimal places in C++
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
Out开发者_如何学运维put
-21.47483648
-21.47483648
-21.47483648
-21.47483648
12.45678988
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;
}
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);
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).
int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 );
temp is probably 32 bits. It can hold up about +- 2 billion. Overflow.
精彩评论