【发布时间】:2018-08-25 10:40:59
【问题描述】:
我有一个表示浮点数的字符串,例如“1000.34”。我想对该字符串应用千位和小数点分隔符规则,例如,它变成“1,000.34”。
我尝试执行以下操作:
ss.imbue(std::locale(ss.getloc(), new mySeparator));
struct mySeparator : std::numpunct<char> {
char do_decimal_point() const {
return '.';
}
char do_thousands_sep() const {
return ',';
}
std::string do_grouping() const {
return "\000"; // Groups of 3
}
};
但这仅适用于数字而非字符串:
double number = 1000.34;
ss << number;
当我拥有一个代表数字的字符串时,我该怎么做?有其他方法吗?
【问题讨论】:
-
使用
std::istringstream解析它,然后将其作为float或double发送到输出。 -
如果我输出“1000.00”会发生什么?我想在
double变量中保留“.00”。 -
看看#What not to do: do not use stringstream for this.
标签: c++ string stringstream