首頁 > 後端開發 > C++ > 主體

如何使用 std::locale 在 C 中用逗號格式化數字?

Barbara Streisand
發布: 2024-10-27 00:19:31
原創
922 人瀏覽過

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

在C 中用逗號格式化數字

在C 中, std::locale 類別提供了一種依賴於區域設定的方法來用逗號格式化數字.

std::locale 與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>
登入後複製

處理雙精確度數

處理雙精確度數

<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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!