The precision of std::to_string(double)

C++C++11

C++ Problem Overview


Is there any way to set the precision of the result when converting a double to string using std::to_string()?

C++ Solutions


Solution 1 - C++

No.

Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size.

Solution 2 - C++

I was just looking for a solution to this as I was overloading the std::cout << operator and therefore it would have been tricky to do the std::stringstream workaround. I solved my problem by using the std::substr() function to locate the decimal and take a chosen number of digits past it.

std::string trimmedString = std::to_string(doubleVal).substr(0, std::to_string(doubleVal).find(".") + precisionVal + 1);

This will give you "precisionVal" 0's after your number.

Ex:

double doubleVal = 3;
int preisionVal = 2

3.000000 becomes 3.00

Solution 3 - C++

I believe that using std::stringstream with setprecision would be the most flexible/portable choice, but if you know your data, as an workaround, you could try to substring the to_string result. For example:

std::string seriesSum(int n)
{
    double sum = 0, div = 1;
    for(int i = 0; i < n; i++) {
      sum += 1.0 / div;
      div += 3;
    }

    return std::to_string(round(sum * 100)/100).substr(0,4);
}

In the code above I'm printing with two decimal places 0.00 by taking the first 4 digits of the string, but it only works because I know the integer part is never going above one digit. You could also use string.find() to search for the decimal separator and use it's position to calculate the size of the substring, making it a bit more dynamic.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser955249View Question on Stackoverflow
Solution 1 - C++ForEveRView Answer on Stackoverflow
Solution 2 - C++Tyler RoseView Answer on Stackoverflow
Solution 3 - C++Daniela PetruzalekView Answer on Stackoverflow