c ++:用逗号格式化数字?

Use*_*ser 69 c++ comma number-formatting

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

示例声明:

std::string FormatWithCommas(long value);
Run Code Online (Sandbox Code Playgroud)

用法示例:

std::string result = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);
// result = "7,800"
// result2 = "5,100,100"
// result3 = "201,234,567,890"
Run Code Online (Sandbox Code Playgroud)

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

(奖金也将用于处理double.)

Jac*_*cob 54

使用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();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我们在哪里知道一个空的语言环境名称意味着"将逗号放入整数"? (15认同)
  • std :: locale("")ctor真的很慢.如果你执行"static std :: locale l(""); ss.imbue(l);",你会获得更好的性能." (3认同)
  • 为了这个,我必须添加`#include <sstream>`. (3认同)
  • 这个功能没有给我留下逗号.我应该设置什么样的地方?我应该让用户设置哪个区域设置?失败. (2认同)

Nod*_*ode 51

您可以像Jacob建议的那样,并imbue使用""语言环境 - 但这将使用系统默认值,但不保证您获得逗号.如果要强制使用逗号(无论系统默认的语言环境设置如何),您都可以通过提供自己的numpunct方面来实现.例如:

#include <locale>
#include <iostream>
#include <iomanip>

class comma_numpunct : public std::numpunct<char>
{
  protected:
    virtual char do_thousands_sep() const
    {
        return ',';
    }

    virtual std::string do_grouping() const
    {
        return "\03";
    }
};

int main()
{
    // this creates a new locale based on the current application default
    // (which is either the one given on startup, but can be overriden with
    // std::locale::global) - then extends it with an extra facet that 
    // controls numeric output.
    std::locale comma_locale(std::locale(), new comma_numpunct());

    // tell cout to use our new locale.
    std::cout.imbue(comma_locale);

    std::cout << std::setprecision(2) << std::fixed << 1000000.1234;
}
Run Code Online (Sandbox Code Playgroud)


car*_*lal 31

我认为以下答案比其他答案更容易:

string numWithCommas = to_string(value);
int insertPosition = numWithCommas.length() - 3;
while (insertPosition > 0) {
    numWithCommas.insert(insertPosition, ",");
    insertPosition-=3;
}
Run Code Online (Sandbox Code Playgroud)

这将快速正确地将逗号插入您的数字串.

  • @ Reb.Cabin std :: to_string是自C++ 11以来的标准 (3认同)
  • 注意:这不适用于-106(输出:-,106) (2认同)