【问题标题】:How to use custom thousand separator and decimal character with std::stringstream?如何在 std::stringstream 中使用自定义千位分隔符和十进制字符?
【发布时间】: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解析它,然后将其作为floatdouble发送到输出。
  • 如果我输出“1000.00”会发生什么?我想在double 变量中保留“.00”。
  • 看看#What not to do: do not use stringstream for this.

标签: c++ string stringstream


【解决方案1】:

不知道为什么你需要使用std::stringstream,但如果你只是想操作字符串,它是数字并从小数点开始每隔第三个数字添加,(如果没有小数点,则添加数字结尾)你可以:

#include <iostream> 
#include <string> 

int main()
{
    std::string num = "-4324234324.234";

    size_t i = num.rfind('.');
    if (i == num.npos) i = num.size();
    const size_t digits = 3 + (num.data()[0] == '-');
    while (i > digits) num.insert(i -= 3, 1, ',');

    std::cout << num << std::endl;
}

https://ideone.com/iRUYJz

-4,324,234,324.234

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多