在 C 中用逗号格式化数字

新手上路,请多包涵

我想写一个方法,它接受一个整数并返回一个用逗号格式化的整数的 std::string

示例声明:

 std::string FormatWithCommas(long value);

示例用法:

 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"

用逗号将数字格式化为 string 的 C++ 方法是什么?

(奖金也将处理 double s。)

原文由 User 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

使用 std::localestd::stringstream

 #include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(T value)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss << std::fixed << value;
    return ss.str();
}

免责声明: 可移植性可能是一个问题,您可能应该查看通过 "" 时使用的语言环境

原文由 Jacob 发布,翻译遵循 CC BY-SA 3.0 许可协议

根据上面雅各布的回答……

这是一个 Windows 解决方案。

 // Compiler : Visual Studio 2022
// I tested on Windows 10 64bit
// DATE: 2022.Sep.15

#include <windows.h>
#include <string>
#include <locale>
#include <sstream>

using namespace std;

template<class T>
std::string FormatWithCommas(T value)
{
    std::stringstream ss;

    // otherwise, use "en_US.UTF-8" as the locale name
    ss.imbue(std::locale("ko_KR.UTF-8"));
    ss << std::fixed << value;

    return ss.str();
}

int main()
{
    LARGE_INTEGER filesize;

    filesize.QuadPart = 1234591046976109;

    // This only works for ASCII strings
    string aaa = (FormatWithCommas(filesize.QuadPart)).c_str();
    std::wstring widestr = std::wstring(aaa.begin(), aaa.end());
    const wchar_t* widecstr = widestr.c_str();

    wprintf_s(L"\nFile Size =  %s bytes\n", widecstr);

    getchar();
    return 0;
}

执行结果如下。

执行结果如下。

原文由 riPmAn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题