」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 std::locale 在 C++ 中使用逗號格式化數字?

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

發佈於2024-11-07
瀏覽:503

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

在C 中用逗號格式化數字

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

std::locale 與std::stringstream

要將數字格式化為帶逗號的字串,可以將std::locale 與std::stringstream 一起使用如下:

#include 
#include 

template
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));  // Use the system's locale
  ss 

用法範例:

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"

處理雙精度數

要將雙精度數格式化為帶逗號的字串,可以使用與上面相同的方法,但程式碼將需要處理小數點:

template
std::string FormatWithCommas(const T& value) {
  std::stringstream ss;
  ss.imbue(std::locale(""));
  ss 

免責聲明:

請注意,上述解決方案的可移植性可能是一個問題,因為傳遞“”時使用的區域設定可能會因係統而異。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3