Development Tip

부동 소수점 값을 변환 할 때 std :: to_string의 정밀도 설정

yourdevel 2020. 12. 8. 20:05
반응형

부동 소수점 값을 변환 할 때 std :: to_string의 정밀도 설정


이 질문에 이미 답변이 있습니다.

C ++ 11에서 std :: to_stringfloat또는 유형의 입력 값이 주어 졌을 때 소수점 6 자리로 기본 설정됩니다 double. 이 정밀도를 변경하기 위해 권장되거나 가장 우아한 방법은 무엇입니까?


비아 정밀 변경할 수있는 방법이 없습니다 to_string()하지만 setprecisionIO 조작하는 대신 사용할 수는 :

#include <sstream>

template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
    std::ostringstream out;
    out.precision(n);
    out << std::fixed << a_value;
    return out.str();
}

참고 URL : https://stackoverflow.com/questions/16605967/set-precision-of-stdto-string-when-converting-floating-point-values

반응형