Rounding to digit Func
Title says all.
Credits to me.
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:
Output:
0.667
3.14298
1.2343
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
