In this article we will discuss different ways to convert double to String or char array with or without precision i.e.

double to String using C++11’s std::to_string

std::to_string is introduced in c++11.

Example to convert double to std::string using to_string is as follows,

Output:

It has default precision of 6 digits and we cannot change it. If you want customised precision then you should use stringstream.

double to String using ostringstream

Header file Required

Example to convert double to std::string using ostringstream is as follows,

Output

For Big Numbers ostringstream will automatically convert it to scientific notation.

double to String with scientific notation using ostringstream

Add std::fixed to stream i.e.

It will force the ostringstream to convert double using fixed-point notation instead of scientific one. For example,

Output

By default, precision is up to max 6 in stringstream’s double to string conversion.

double to String with Custom Precision using ostringstream

Header file Required

To convert Double to String with Custom Precision set precision in stringstream i.e.

Let’s set precision to 2 i.e.

Check this,

Output:

double to String / Char array using C’s snprintf

Output

double to String boost’s lexical_cast

Header file Required

Example,

Output

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.