将浮点数转换为字符串,设置精度&小数位数? [英] Convert float to string with set precision & number of decimal digits?

查看:527
本文介绍了将浮点数转换为字符串,设置精度&小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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 )且没有指数部分。


setprecision


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 to fixed.

When floatfield is set to fixed, 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.

这篇关于将浮点数转换为字符串,设置精度&amp;小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆