首页 > 解决方案 > 将 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

标签: c++

解决方案


如果您只想打印出来:

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;

推荐阅读