Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

floating point - Float formatting in C++

How do you format a float in C++ to output to two decimal places rounded up? I'm having no luck with setw and setprecision as my compiler just tells me they are not defined.

cout << "Total : " << setw(2) << total << endl;

total outputs: Total : 12.3961

I'd like it to be: 12.40 or 12.39 if it's too much work to round up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to include <iomanip> and provide namespace scope to setw and setprecision

#include <iomanip>
std::setw(2)
std::setprecision(5)

try:

cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;

or

 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;

iostream provides precision function, but to use setw, you may need to include extra header file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...