C++ 四舍五入到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14596236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding to 2 decimal points
提问by averageUsername123
I've used the following to round my values to 2 decimal points:
我使用以下内容将我的值四舍五入到 2 个小数点:
x = floor(num*100+0.5)/100;
and this seems to work fine; except for values like "16.60", which is "16.6".
这似乎工作正常;除了像“16.60”这样的值,即“16.6”。
I want to output this value like "16.60".
我想输出这个值,比如“16.60”。
The way I'm outputting values is the following:
我输出值的方式如下:
cout setw(12) << round(payment);
I've tried the following:
我尝试了以下方法:
cout setw(12) << setprecision(2) << round(payment);
But that gave me answers like
但这给了我答案
1.2e+02
How can I output the values correctly?
如何正确输出值?
回答by billz
This is because std::setprecision
doesn't set the digits after the decimal point but the significant digits if you don't change the floating point format to use a fixed number of digits after the decimal point. To change the format, you have to put std::fixedinto your output stream:
这是因为std::setprecision
如果您不更改浮点格式以使用小数点后的固定位数,则不会设置小数点后的数字而是有效数字。要更改格式,您必须将std::fixed放入输出流中:
double a = 16.6;
std::cout << std::fixed << std::setprecision(2) << a << std::endl;
回答by gerrytan
you can use printf / sprintf or other similar functions. Following code will format floating point value into two digits after decimals. Refer to the printf manual for more formatting info
您可以使用 printf / sprintf 或其他类似功能。以下代码将浮点值格式化为小数点后两位。有关更多格式信息,请参阅 printf 手册
float f = 1.234567
printf("%.2f\n", f);
回答by Drew Dormann
From Trevor Boyd Smith's comment:
来自特雷弗博伊德史密斯的评论:
If you are allergic to printf and friends there is the type safe C++ version in
#include <boost/format.hpp>
which you can use to do:
如果您对 printf 和朋友过敏,则
#include <boost/format.hpp>
可以使用类型安全的 C++ 版本来执行以下操作:
float f = 1.234567;
cout << boost::format("%.2f") % f << endl;