+ 2
Rounding specific digits in C++
What is the most efficient and simple way to round a specific digit in C++? Like for example what if i wanted to round 5122 to the nearest thousand? Or round 17.922 to the nearest hundredth? How exactly do i do it? And if possible can you also provide me an example for your method in code?
6 Answers
+ 4
Dronto, it is straightforward enough to write a custom round function that handles both requirements.
float nearest(float a, float d) {
   return (int)(a/d + 0.5)*d;
}
Parameter a is the number to be rounded.
Parameter d is the desired place value.
e.g., d=100 to get nearest 100
    d=0.001 to get nearest 1000th
The function shifts the decimal point by dividing by d. This automatically moves the decimal either left or right to where it is needed to round. Then it adds 0.5 in order to cause rounding up if the fractional part is 0.5 or higher, else it will round down by truncation, and it converts the type to integer in order to truncate the fractional part. Finally, it multiplies by d in order to restore the decimal point to its original position.
Examples:
nearest(17.922, 0.01)Â <--- returns 17.92
nearest(1522, 1000) <--- returns 2000
https://code.sololearn.com/ciBB0uWR6J9S/?ref=app
+ 5
round(inum / 1000.f)*1000
round(fnum / 100.f)*100
Just a quick solution, there might be better ones.
+ 4
Use ceil function to round off a number
+ 4
// Hope this helps
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << round(17.922 * 100.0) / 100.0;
return 0;
}
+ 4
Hasnain [ACTIVE CHALLENGER] the ceil function will not do what Dronto is asking. It always rounds up. The round function rounds to the nearest.
+ 4
Brian's and SoloProg's answers are the two best...
SoloProg provided a simple clever solution that i understood right away by looking at the code.
Brain provided me with an another solution that's also pretty good and proceeded to explain everything too (respect)... which is why he gets the best answer checkmark.
Also thanks to everyone else who tried to help me!