c++ - 将 float 转换为 std::string 而不会丢失精度。我也不想使用 sprintf
问题描述
我想在 std::string 中转换浮点值,即 3.14159267 我不想使用 sprintf
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.14159267);
std::cout<<pi<<std::endl;
return 0;
}
我得到的结果为 3.141593
解决方案
如果您只想打印出来:
std::cout<< std::setprecision(9) << 3.14159267 << std::endl;
如果要设置字符串的精度:
double pi = 3.14159265359;
std::stringstream stream;
stream << std::setprecision(9) << pi;
std::string pi_string = stream.str();
std::cout<< "Pi:" << pi_string << std::endl;
推荐阅读
- json - 从 JSON 反应地图对象和嵌入对象并转换为单个数组以获取状态
- java - 如何为数组中的每个元素动态更改日期
- python - 检索 Excel 工作簿连接属性
- c# - 如何获取/设置并不总是实现的接口的属性
- sql - oracle验证插入然后删除动态表
- android - MediaPlayer (Samsung Oreo 8.0) 的原生崩溃 tgkill+8
- scala - 如何在无形中创建生成的对象
- android - 重新加载的方法 应用程序的完整状态?
- python - scattermapbox plot.ly dash 没有出现
- r - 将 ggplot2 与 Rshiny 一起使用:ggplot y 轴上显示的级别不正确