ホームページ  >  記事  >  バックエンド開発  >  std::locale と std::stringstream を使用して C で数値をカンマでフォーマットする方法

std::locale と std::stringstream を使用して C で数値をカンマでフォーマットする方法

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-26 21:27:02116ブラウズ

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

C でのカンマを使用した数値の書式設定

はじめに:

C では、次の数値を書式設定します。カンマは、特に通貨や大きな数値を表示する場合によく使用されるタスクです。このチュートリアルでは、整数と double にカンマを追加する効率的な方法を示します。

メソッド:

数値をカンマでフォーマットするには、std::locale を利用します。 および std::stringstream.

ステップ 1: std::locale の使用

<code class="cpp">std::stringstream ss;
ss.imbue(std::locale(""));</code>

std:: locale を使用すると、文字列フォーマットのロケールを設定できます。空の文字列 ("") を使用すると、ロケールがユーザーのデフォルトのシステム設定に設定されます。

ステップ 2: std::stringstream を使用する

<code class="cpp">ss << std::fixed << value;

std::stringstream は、フォーマットされた文字列を構築するために使用されます。小数点を維持するために std::fixed を使用してストリームに値を挿入します。

整数の書式設定:

整数の場合は、単純に呼び出します。 FormatWithCommas() メソッドは次のようになります。

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

Double の書式設定:

Double の場合は、同じメソッドを使用しますが、少し変更します。 std::fixed:

<code class="cpp">ss << std::fixed << std::setprecision(2) << value;

std::setprecision() を使用すると、10 進数 2 桁のみが表示されるようになります。

使用例:

<code class="cpp">#include <cmath>

std::string FormatWithCommas(double value)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss << std::fixed << std::setprecision(2) << value;
    return ss.str();
}

int main()
{
    double pi = std::atan(1.0) * 4.0;
    std::string result = FormatWithCommas(pi);
    std::cout << result << "\n";
}</code>

出力:

3.14

以上がstd::locale と std::stringstream を使用して C で数値をカンマでフォーマットする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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