The precision of std::to_string(double)
Is there any way to set the precision of the result when converting a double to string using std::to_string()
?
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.