【问题标题】:How to add commas to a number if it's declared as a double?如果将数字声明为双精度,如何在数字中添加逗号?
【发布时间】:2018-04-05 14:17:56
【问题描述】:

假设我希望用户输入一个数字,并且我希望该数字用逗号分隔。

示例。

double attemptOne;

cout << "Enter a number: ";
cin >> attemptOne;  //user inputs 10000.25
cout << endl << attemptOne;  //I want to cout 10,000.25

我是 C++ 新手,所以请帮助我 我不是在谈论将小数更改为逗号,而是让程序知道数字何时大于 999 以添加逗号,例如 1,000.25 10,000.25 100,000.25。我也不想使用本地

【问题讨论】:

  • 千位分隔符通常是系统区域设置的一部分。
  • 希望副本就足够了。但是如果你想要其他格式,例如像 1,23,456.78 这样的印度分离然后请竖起。
  • OP 没有询问小数点分隔符。他在问千位分隔符。 “1,000.25”中的“,”。虽然,它仍然是重复的。 stackoverflow.com/questions/17530408/…
  • @Bathsheba 最近的编辑显示 OP 想要千位分隔符,而不是小数点。

标签: c++


【解决方案1】:

也许,因为你需要一个字符串,你也可以读取一个字符串,然后解析它,从小数点开始每隔 3 位添加逗号,如果不存在小数点,则从末尾添加逗号:

#include <iostream>
#include <string>

int main()
{
    std::string attemptOne;
    std::cout << "Enter a number: ";
    std::cin >> attemptOne;

    size_t dec = attemptOne.rfind('.');
    if (dec == std::string::npos)
        dec = attemptOne.size();

    while (dec > 3)
        attemptOne.insert(dec -= 3, 1, ',');

    std::cout << attemptOne << std::endl;
}

【讨论】:

  • 谢谢先生,这真的帮了我大忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
相关资源
最近更新 更多