1

I'm currently coding a project for my Computer Science module but I'm having the problem of my string value defaulting to scientific notation if there are too many decimal places in the double value.

I've tried the obvious solution with ostringstream and .str() but it makes it into notation. I have to compile to the C++98 standard, so I cannot use modern solutions like std::to_string.

I need the value to be casted into a string but it needs to maintain its formatting. any help would be appreciated.

user4581301
  • 33,082
  • 7
  • 33
  • 54
Matthew
  • 11
  • 2
  • 1
    Does this answer your question? [Double to string conversion without scientific notation](https://stackoverflow.com/questions/1546113/double-to-string-conversion-without-scientific-notation) – MrProgrammer May 28 '20 at 18:03
  • Not a C# question, @UtkarshGupta – user4581301 May 28 '20 at 18:04
  • 1
    Does this answer your question? [Turn off scientific notation on float](https://stackoverflow.com/questions/6301547/turn-off-scientific-notation-on-float) Or this: https://stackoverflow.com/questions/6301547/turn-off-scientific-notation-on-float – James Morris May 28 '20 at 21:37

2 Answers2

6

I would use:

std::to_string(myDouble);
  • unfortunately requires C++11 – QuentinUK May 28 '20 at 19:59
  • In 2020 it's truly unfortunate if you don't have access to C++11. It happens, I maintain some pretty old C++ code my organization will not allow me to change, but I only write new stuff in C++03 or C++98 on demand and only if there is a really, really good reason. – user4581301 May 28 '20 at 20:21
0

If you use at least C++17, you could use std::to_chars() from #include <charconv>.

// `512` is here arbitrary, it is the max size of the output string. 
// Smaller values should be sufficient.
char buffer[512];
// Here 'std::chars_format::fixed' tells the `std::to_chars()` to 
// not use the scientific notation.
char* end = std::to_chars(std::begin(buffer), std::end(buffer), myDouble, std::chars_format::fixed).ptr;
// `end` the one-past-the-end pointer of the characters written to `buffer`.

This method is probably faster than the Emilien Lemaire's answer, however it's more verbose, and more error-prone. So this answer is only provided for completeness (as the performance gain may not worth it).

Moreover, unlike std::to_string(), the output string is locale-insensitive, so the double will always be formatted in the C locale (english locale).

Hubert Gruniaux
  • 124
  • 2
  • 11
  • Unfortunately, my course limits us to c++98 in order to make us understand the more fundamental principles of c++. I have tried to_string() but that too cuts it down to notation. – Matthew May 28 '20 at 19:55
  • Then you could use `std::sprintf(myBuffer, "%f", myDouble)` (available in C++98). The format `%f` specify to use the decimal notation. See https://en.cppreference.com/w/cpp/io/c/fprintf for more detail. – Hubert Gruniaux May 28 '20 at 20:03