C ++浮点格式 [英] C++ float formatting
问题描述
如何格式化C ++中的浮点数以输出到小数点后两位?我没有运气与 setw
和 setprecision
,因为我的编译器只是告诉我他们是未定义
。
cout< Total:<< setw(2)<<总< endl;
总输出:总计:12.3961
我想要的是: 12.40
或 12.39
如果工作太多
您需要包括< iomanip>
并为 setw和setprecision提供命名空间范围
#include< iomanip> ;
std :: setw(2)
std :: setprecision(5)
try:
cout.precision(5)
cout<< Total:<< setw(4)<< floor(total * 100)/ 100 < endl;
或
cout<< Total:<< setw(4)<<细胞(总* 10)/ 10 < endl;
iostream提供了精确的函数,但是要使用setw,你可能需要包含额外的头文件。 p>
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.
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.
这篇关于C ++浮点格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!