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::locale与std::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)
免责声明:可移植性可能是一个问题,您应该查看""传递时使用的语言环境
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)
这将快速正确地将逗号插入您的数字串.
| 归档时间: |
|
| 查看次数: |
63615 次 |
| 最近记录: |