在C ++中将Double转换为String

时间:2020-12-24 16:41:14

I am having some issues trying to convert a double to C++ string. Here is my code

我在尝试将double转换为C ++字符串时遇到了一些问题。这是我的代码

std::string doubleToString(double val)
{
    std::ostringstream out;
    out << val;
    return out.str();
}

The problem I have is if a double is being passed in as '10000000'. Then the string value being returned is 1e+007

我遇到的问题是如果将double传递为'10000000'。然后返回的字符串值是1e + 007

How can i get the string value as "10000000"

如何将字符串值设为“10000000”

3 个解决方案

#1


#include <iomanip>
using namespace std;
// ...
out << fixed << val;
// ...

You might also consider using setprecision to set the number of decimal digits:

您还可以考虑使用setprecision来设置小数位数:

out << fixed << setprecision(2) << val;

#2


#include <iomanip>

std::string doubleToString(double val)
{
   std::ostringstream out;
   out << std::fixed << val;
   return out.str();
}

#3


You can also set the minimum width and fill char with STL IO manipulators, like:

您还可以使用STL IO操纵器设置最小宽度和填充字符,例如:

out.width( 9 );
out.fill( ' ' );

#1


#include <iomanip>
using namespace std;
// ...
out << fixed << val;
// ...

You might also consider using setprecision to set the number of decimal digits:

您还可以考虑使用setprecision来设置小数位数:

out << fixed << setprecision(2) << val;

#2


#include <iomanip>

std::string doubleToString(double val)
{
   std::ostringstream out;
   out << std::fixed << val;
   return out.str();
}

#3


You can also set the minimum width and fill char with STL IO manipulators, like:

您还可以使用STL IO操纵器设置最小宽度和填充字符,例如:

out.width( 9 );
out.fill( ' ' );