简体   繁体   English

在C ++中将Double转换为String

[英]Converting Double to String in C++

I am having some issues trying to convert a double to C++ string. 我在尝试将double转换为C ++字符串时遇到了一些问题。 Here is my code 这是我的代码

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'. 我遇到的问题是如果将double传递为'10000000'。 Then the string value being returned is 1e+007 然后返回的字符串值是1e + 007

How can i get the string value as "10000000" 如何将字符串值设为“10000000”

#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;
#include <iomanip>

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

You can also set the minimum width and fill char with STL IO manipulators, like: 您还可以使用STL IO操纵器设置最小宽度和填充字符,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM