Is there a smarter way than 'setprecision()' to specify the number of decimal points? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

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; }

8th Aug 2020, 9:04 AM
Solus
Solus - avatar
1 Answer
+ 2
Looks like you want to set the precision to the last 2 digits after the decimal point. You can use std::fixed with std::setprecision(2) to make it display 2 digits after the decimal point regardless of the rest before it.
8th Aug 2020, 9:40 AM
Dennis
Dennis - avatar