Home c++ How can I make sure that only a certain number of digits...

How can I make sure that only a certain number of digits after the decimal point are displayed?

Author

Date

Category


Answer 1, authority 100%

C style

printf ("% .2f \ n", val);
printf ("% .1f \ n", val);

C++ style

cout & lt; & lt; fixed;
cout.precision (2);
cout & lt; & lt; val & lt; & lt; endl;

Answer 2, authority 20%

cout & lt; & lt; fixed;
cout.precision (2);
cout & lt; & lt; val & lt; & lt; endl;

Important: precision does math rounding.


Answer 3, authority 10%

// I don’t remember how the C++ style is tricky, but the C style is even easier
# include & lt; stdio.h & gt;
int main () {
double pi = 3.14159;
printf ("%. 2f", pi);
// the result will be such a view: 3.14
return 0;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions