The precision of std::to_string(double)

后端 未结 3 1681
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 13:31

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

3条回答
  •  孤独总比滥情好
    2020-11-30 13:56

    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

提交回复
热议问题