How to convert double to string with precision for total number of digits(both left and right side of the decimal)?

  c++, c++11

I am looking for a way to convert double to string in c++ such that total number of digits remain to be 10 irrespective of how many are present before and after the decimal point and irrespective of the zeroes. Examples for better understanding:

0.00000000000000000000 =expected outcome> 0.0000000000

12345.00000000000000000 =expected outcome> 12345.00000

-15.123456789012 =expected outcome> -15.12345678

I couldnt find any relevant answer. For the methods like snprintf, std::setprecision with ostringstream, to_string, Boost’s lexical_cast, some of the above case fails.

Example of code:

double num = 12345.0000000000001;

std::ostringstream streamObj2;

streamObj2 << std::fixed <<  std::setprecision(10) << num;

std::string strObj2 = streamObj2.str();

std::cout  << strObj2 << 'n';

The output = 12345.0000000000, which is not what I am expecting. Removing std::fixed gives output as 12345

What I require = 12345.00000

Please help me, thanks.

Source: Windows Questions C++

LEAVE A COMMENT