Rounding to nearest digit Func

Posts 1–5 of 5 · Page 1 of 1
Rounding to digit Func
Title says all.

Credits to me.


Code:
double round(double n,int digit){

	double x = n*pow(10,digit+1);
		
	return (double) ((int)(x+10*((int)x%10>=5))-(int)x%10) / pow(10,digit+1);

}

The function casts a number to integer and shifts the digits to as many as required plus one. For example the number

1234.567 to 10^(digit+1).

We want one more digit as well because we need the check if the last digit is larger or equal to 5. Let say we wanted to round to the 2nd digit. We will cast to integer and like so:

1234.567 * 10^(2+1) = 1234567.

In the complicated return line, we can break it down. First we take the last digit (7) to check if it is bigger than 5 and if we need to round. It is so we add 10 to it which is the actual digit we need to change.

1234577

Since we used the last digit we have to get rid of it so we subtract it (int)x%10).

1234570

Now we have to change the number back into a double so we divide it by number of digits we moved before and cast back to double.

1234570/10^(2+1)
1234.57

And there we go! We rounded the number.

Example of usage:

Code:
#include <iostream>

using namespace std;

double round(double n,int digit){

	double x = n*pow(10,digit+1);
		
	return (double) ((int)(x+10*((int)x%10>=5))-(int)x%10) / pow(10,digit+1);

}

int main(void){

cout<<round(2.0/3.0,3)<<endl;
cout<<round(3.142982,5)<<endl;
cout<<round(1.23432,4)<<endl;


}

Output:

0.667
3.14298
1.2343
Code:
float LOLFLOAT = 1.333337f;
printf("%.3f", LOLFLOAT);
output:
1.333

Nice work =)
Quote Originally Posted by Hell_Demon View Post
Code:
float LOLFLOAT = 1.333337f;
printf("%.3f", LOLFLOAT);
output:
1.333

Nice work =)
I agree totally. I have a prime # finder if you want to check it out. Not HD the other guy. But yea so you can learn more C++.
The point isnt dropping the decimal but ROUNDING the decimal. >=(

Code:
float LOLFLOAT 1.3336

printf("%lf",round(LOLFLOAT,3));
1.334
1.333>3<
less then 5, thus rounded down ;P
Posts 1–5 of 5 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

None

Need help?