在 C++ 中作为货币输出

Output as currency in C++

我有一个简单的 C++ 命令行程序,我从用户那里获取输入,然后将其显示为价格、货币符号、逗号分隔每组 3 个值、一个小数点和两个小数位即使它们为零也会显示。

我想要实现的示例:

100 => £100.00
101.1 => £101.10
100000 => £100,000.00

这是我目前的方法:

void output_price() {
    int price;

    cout << "Enter a price" << endl;
    cin >> price;
    string num_with_commas = to_string(price);
    int insert_position = num_with_commas.length() - 3;
    while (insert_position > 0) {
        num_with_commas.insert(insert_position, ",");
        insert_position -= 3;
    }

    cout << "The Price is: £" << num_with_commas << endl;
}

部分有效,但不显示小数 point/places。

1000 => £1000

如果我将价格更改为浮动价格或双倍价格,它会给我以下信息:

1000 => £10,00.,000,000

我试图让事情变得简单并避免创建货币 class,但不确定这在 C++ 中是否可行。

感谢任何帮助。

逻辑错误在这里:

int insert_position = num_with_commas.length() - 3;

原值num_with_commas的点后可以有任意位数,包括没有点;此外,您无法控制它,因为 the format applied by std::to_string is fixed.

如果您想继续使用 std::to_string,您需要进行一些更改:

  • 找到点 '.' 字符的位置。
  • 如果点存在,并且其后的字符数小于2,继续追加零"0"直到点'.'是倒数第三个字符
  • 如果有点,并且后面有两个以上的字符,去掉字符串的尾部,使点后正好有两个字符
  • 如果点不存在,将 ".00" 附加到字符串

插入点的其余算法将正常工作。