Is there a smarter way than 'setprecision()' to specify the number of decimal points?
Trying to get user input rounded to two decimal places. Been using 'setprecision()' to round to the nearest hundredth place. However, this technique cannot be generalized... That is, we have to keep adding 'else if' blocks to address the potential for big numbers that the user might input (refer to example below). Is there a smarter way to do this? ============================================ #include <iostream> #include <math.h> #include <iomanip> using namespace std; int main() { int c = 5; int k; double total; cin >> k; if (k==1){ cout << c * 1.07; } else if (k>1 && k<20){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(4) << total; } else if (k>20 && k<200){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(5) << total; } else if (k>1 && k<2000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(6) << total; } else if (k>1 && k<20000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(7) << total; } else if (k>1 && k<200000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(8) << total; } else if (k>1 && k<2000000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(9) << total; } else if (k>1 && k<20000000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(10) << total; } else if (k>1 && k<200000000){ total = (k*c); total = total * 0.9 * 1.07; cout << setprecision(11) << total; } return 0; }