>  기사  >  백엔드 개발  >  std::locale을 사용하여 C에서 쉼표로 숫자 형식을 지정하는 방법은 무엇입니까?

std::locale을 사용하여 C에서 쉼표로 숫자 형식을 지정하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-27 00:19:31923검색

How to Format Numbers with Commas in C   Using std::locale?

C에서 쉼표를 사용하여 숫자 서식 지정

C에서 std::locale 클래스는 쉼표를 사용하여 숫자 서식을 지정하는 로케일별 방법을 제공합니다. .

std::locale with std::stringstream

숫자를 쉼표가 있는 문자열 형식으로 지정하려면 std::stringstream과 함께 std::locale을 사용할 수 있습니다. 다음과 같습니다:

<code class="cpp">#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));  // Use the system's locale
  ss << std::fixed << value;
  return ss.str();
}</code>

사용 예:

<code class="cpp">std::string result1 = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);

// result1 = "7,800"
// result2 = "5,100,100"
// result3 = "201,234,567,890"</code>

Double 처리

Double 형식을 쉼표가 있는 문자열의 경우 위와 동일한 접근 방식을 사용할 수 있지만 코드는 소수점을 처리해야 합니다.

<code class="cpp">template<class T>
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));
  ss << std::fixed << std::setprecision(2) << value;
  return ss.str();
}</code>

면책 조항:

""가 전달될 때 사용되는 로케일이 시스템에 따라 다를 수 있으므로 위 솔루션의 이식성은 문제가 될 수 있습니다.

위 내용은 std::locale을 사용하여 C에서 쉼표로 숫자 형식을 지정하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.