将浮点数转换为字符串,设置精度&小数位数? [英] Convert float to string with set precision & number of decimal digits?
问题描述
如何在C ++中将float转换为字符串,同时指定precision和amp;小数位数?
例如: 3.14159265359 - > 3.14
double pi = 3.14159265359;
stringstream stream;
stream<<固定< setprecision(2)<< pi;
string s = stream.str();
使用固定浮点符号 b
将 str 流的
floatfield
格式标志设置为固定
。
当
floatfield
设置为fixed
,浮点值使用定点符号表示:该值由精确字段(precision $)指定的小数部分中的多位数表示c $ c>)且没有指数部分。
How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?
For example: 3.14159265359 -> "3.14"
double pi = 3.14159265359;
stringstream stream;
stream << fixed << setprecision(2) << pi;
string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
这篇关于将浮点数转换为字符串,设置精度&小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!