0

I have a double in format xxxxx.yyyy, for example 0.001500.

I would like to convert it into wstring, formatted with scientific notation. This is the result I want: 0.15e-2.

I am not that experienced with C++, so I checked std::wstring reference and haven't found any member function that can do this.

I have found similar threads here on Stack Overflow but I just do not know how to apply those answers to solve my problem especially as they do not use wchar.

I have tried to solve this myself:

// get the value from database as double
double d = // this would give 0.5

// I do not know how determine proper size to hold the converted number 
// so I hardcoded 4 here, so I can provide an example that demonstrates the issue
int len = 3 + 1;  // + 1 for terminating null character
wchar_t *txt = new wchar_t[3 + 1];
memset(txt, L'\0', sizeof(txt));
swprintf_s(txt, 4, L"%e", d);
delete[] txt;

I just do not know how to allocate big enough buffer to hold the result of the conversion. Every time I get buffer overflow, and all the answers here from similar thread estimate the size. I really would like to avoid this type of introducing "magic" numbers.

I do not know how to use stringstream either, because those answers did not convert double into wstring with scientific notation.

All I want is to convert double into wstring, with resulting wstring being formatted with scientific notation.

Community
  • 1
  • 1
AlwaysLearningNewStuff
  • 2,939
  • 3
  • 31
  • 84

1 Answers1

3

You can use std::wstringstream and the std::scientific flag to get the output you're looking for as a wstring.

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

int main(int argc, char * argv[])
{
    double val = 0.001500;
    std::wstringstream str;
    str << std::scientific << val;
    std::wcout << str.str() << std::endl;
    return 0;
}

You can also set the floating-point precision with additional output flags. Take a look at the reference page for more output manipulators you can use. Unfortunately I don't believe your sample expected output is possible since the correct scientific notation would be 1.5e-3.

E. Moffat
  • 3,165
  • 1
  • 21
  • 34
  • Just one more question: I have to do the conversion for multiple `double`s, can I reuse the same `wstringstream` instead of making new one for every operation? If I can reuse `wstringstream ` can you edit your answer to show me how? Thank you for helping. – AlwaysLearningNewStuff Nov 26 '15 at 23:25
  • You'll need to clear the stream between uses otherwise the numbers will be appended after each other into the stream. See this SO question for details on how to do this: http://stackoverflow.com/questions/834622/best-way-to-empty-stringstream – E. Moffat Nov 26 '15 at 23:44