Development Tip

정밀도와 소수 자릿수가 지정된 문자열로 float를 변환 하시겠습니까?

yourdevel 2020. 11. 7. 10:37
반응형

정밀도와 소수 자릿수가 지정된 문자열로 float를 변환 하시겠습니까?


정밀도와 소수 자릿수를 지정하는 동안 C ++에서 float를 문자열로 어떻게 변환합니까?

예를 들면 : 3.14159265359 -> "3.14"


일반적인 방법은 다음을 사용하는 것입니다 stringstream.

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

고정 참조

고정 부동 소수점 표기법 사용

str 스트림 floatfield형식 플래그를로 설정합니다 .fixed

가로 floatfield설정 fixed되면 부동 소수점 값이 고정 소수점 표기법을 사용하여 기록됩니다. 값은 정밀도 필드 ( precision)에 지정된대로 소수점 부분에 지수 부분없이 정확하게 숫자로 표시됩니다 .

setprecision .


에 대한 기술적 인 목적의 변환 XML 또는 JSON 파일, C ++ (17 명)을 정의의 데이터 저장과 같은, 바꿀수 기능의 가족.

준수 컴파일러 (작성 당시 부족함)를 가정하면 다음과 같은 것을 고려할 수 있습니다.

#include <array>
#include <charconv>

double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
                               std::chars_format::fixed, 2);
if (ec == std::errc{}) {
    std::string s(buffer.data(), ptr);
    // ....
}
else {
    // error handling
}

이런 종류의 작업을 수행하는 일반적인 방법은 "문자열로 인쇄"하는 것입니다. C ++에서는 std::stringstream다음과 같은 것을 사용하는 것을 의미합니다 .

std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();

또 다른 옵션은 snprintf다음과 같습니다.

double pi = 3.1415926;

std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);

데모 . 오류 처리를 추가해야합니다 (예 :written < 0.


{fmt} 라이브러리fmt::format함수를 사용할 수 있습니다 .

#include <fmt/core.h>

int main()
  std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}

2정밀도는 어디에 있습니까 ?

This formatting facility has been proposed for standardization in C++: P0645. Both P0645 and {fmt} use a Python-like format string syntax which is similar to printf's but uses {} as delimiters instead of %.


Here I am providing a negative example where your want to avoid when converting floating number to strings.

float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;

You get

99463 99.463 99.462997

Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.

I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.

string ftos(float f, int nd) {
   ostringstream ostr;
   int tens = stoi("1" + string(nd, '0'));
   ostr << round(f*tens)/tens;
   return ostr.str();
}

참고URL : https://stackoverflow.com/questions/29200635/convert-float-to-string-with-precision-number-of-decimal-digits-specified

반응형