ホームページ  >  記事  >  バックエンド開発  >  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::locale と std::stringstream を使用できます。次のように:

<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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。