【问题标题】:Currency format using double values使用双值的货币格式
【发布时间】:2014-02-28 19:39:36
【问题描述】:

如何从双值中获取货币格式?以下 sn-p 适用于整数,但不适用于双精度数?!

#include <locale.h>
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

int main(void)
{
    ostringstream stream;
    stream.imbue(std::locale(""));
    stream << setprecision(3) <<194663.33;
    string stringValue = stream.str();
    cout << stringValue;
    return 0;
}

【问题讨论】:

  • 我使用的是 M$ Visual Studio 2012,而在 Linux 下使用 gcc 并没有遇到这个问题(我使用了sprintf(buffer, WString("%'.3f")
  • 你怎么知道它不适用于double?您能否向我们展示使用intdouble 的输出以及您的预期?
  • 你不应该用二进制浮点数表示货币值
  • for:194663.33 我得到了1.95e+005 for:194663 我得到了194,663
  • @DieterLücking 不幸的是我必须使用双打

标签: c++ format currency


【解决方案1】:

类似这样的:

#include <iostream>
#include <iomanip>

class punct_facet: public std::numpunct<char>
{
    char do_decimal_point() const { return '.'; }
    char do_thousands_sep() const { return ','; }
    std::string do_grouping() const { return "\03"; }
};
void main()
{
    std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet));
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Formatted number: " << 194663.33 << std::endl;
}

输出:

Formatted number: 194,663.33

您可以在此处找到更多信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-06
    • 2015-10-24
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2013-10-18
    相关资源
    最近更新 更多