Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The precision of std::to_string(double)

Tags:

c++

c++11

People also ask

What is the precision of double in C++?

The C++ double should have a floating-point precision of up to 15 digits as it contains a precision that is twice the precision of the float data type. When you declare a variable as double, you should initialize it with a decimal value. For example, 3.0 is a decimal number.

How precise is a double?

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

How many decimals of precision does a double have?

double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.

Why is double not precise in C++?

In a typical implementation, a double has about 15 digits of precision total. It doesn't matter much whether those are before or after the decimal point, it's just a total of 15 digits. In your case, the original number is about 20 digits, so five are lost immediately.


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.


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


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.