【问题标题】:How do you use put_money in VC++?你如何在 VC++ 中使用 put_money?
【发布时间】:2021-08-03 03:16:03
【问题描述】:
Win7-64
Win10-64
VC++ 16.9.4

我正在尝试使用 put_money 来:

  • 插入货币符号 ($)
  • 为千位/小数点插入区域分隔符

特别是对于 locale("en-US") if:

    long double x = 1234567891;
    cout << put_money(x) << endl;

然后我希望看到像 $123,456.79 这样的输出,并且我看过的示例似乎同意。相反,我看到的是 123456。

我对语言环境的使用是:

 # include <fstream>
 # include <sstream>
 # include <string>

ofstream repout;
void openFile(string filename) {
   if (filename.empty()) {
      cout << "Filename missing" << endl;
   } else {
      try {
         repout.open(filename);
         locale mylocale("");
         repout.rdbuf()->pubimbue(mylocale);
      } catch (exception& e) {
         stringstream str;
         str << "Unable to open: " << filename << ": " << e.what();
         cout << str.str() << endl;
      }
   }
}; // int openFile(string filename) 

【问题讨论】:

  • 它可能取决于操作系统和许多其他设置。在 Linux 上,请参阅 locale(7)
  • 你能显示一个minimal reproducible example 你设置语言环境的地方吗?
  • 请参阅this,了解在您的实施中打印出所有可用语言环境的示例。
  • 喜欢你的标题...一个问题,问如何把钱投入风险投资:-P
  • @JohnFilleau 下面的例子(我希望它可读)

标签: c++ visual-c++ c++17


【解决方案1】:

我决定编写自己的一小段代码,而不是等待解决方案。似乎有效。

# include <sstream>
# include <string>

string putmoney(double x) {
   static const string money = "$";                      //!< monetary symbol
   static const string thou  = ",";                      //!< thousands symbol
   stringstream out;
   out << setprecision(2) << fixed << x;                 //  create money

   string tmp = out.str()                                //!< copy money into temporary string
        , str = money;                                   //!< putmoney output string

   int size = tmp.size() - ((x < 0) ? 4 : 3)             //!< size w/o fraction, minus sign and decimal point
     , th   = (size - 1 )/ 3                             //!< number of thousands
     , rem  = size % 3;                                  //!< number of excess char

   if (th == 0) return str + tmp;                        //   0.0 < number < 999.99

   rem  = (rem == 0) ? 3 : rem;                          //   move the three leading characters
   rem += (x < 0) ? 1 : 0;                               //   add one if the number is negative
   str += tmp.substr(0, rem);                            //   produces $# or $-#

   for (; th > 0; th--) {                                //   insert thousands seperators
      str += thou + tmp.substr(rem, 3);
      rem += 3;
   }
   str += tmp.substr(tmp.size() - 3, 3);                 //   move fractional part
   return str;
}; // string putmoney(double x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2016-05-15
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多