【问题标题】:c++: How do I format a double to currency with dollar sign?c ++:如何将双精度格式设置为带有美元符号的货币?
【发布时间】:2012-11-22 17:36:12
【问题描述】:

我有一个函数,它接受一个双精度并将其作为带有千位分隔符的字符串返回。你可以在这里看到它:c++: Format number with commas?

#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(T value)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss << std::fixed << value;
    return ss.str();
}

现在我希望能够将其格式化为带有美元符号的货币。具体来说,如果给定 20500 的双倍,我想得到一个字符串,例如“$20,500”。

在负数的情况下添加美元符号不起作用,因为我需要“-$5,000”而不是“$-5,000”。

【问题讨论】:

标签: c++ string string-formatting currency dollar-sign


【解决方案1】:

我认为你唯一能做的就是

ss << (value < 0 ? "-" : "") << "$" << std::fixed << std::abs(value);

您需要特定的语言环境来打印千位分隔符。

【讨论】:

    【解决方案2】:
    if(value < 0){
       ss << "-$" << std::fixed << -value; 
    } else {
       ss << "$" << std::fixed << value; 
    }
    

    【讨论】:

    • 其实我喜欢它胜过我的解决方案。
    【解决方案3】:

    这是我用来学习从here 提取的格式化货币的示例程序。试着把这个程序分开,看看你能用什么。

    #include <iostream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    void showCurrency(double dv, int width = 14)
    {
        const string radix = ".";
        const string thousands = ",";
        const string unit = "$";
        unsigned long v = (unsigned long) ((dv * 100.0) + .5);
        string fmt,digit;
        int i = -2;
        do {
            if(i == 0) {
                fmt = radix + fmt;
            }
            if((i > 0) && (!(i % 3))) {
                fmt = thousands + fmt;
            }
            digit = (v % 10) + '0';
            fmt = digit + fmt;
            v /= 10;
            i++;
        }
        while((v) || (i < 1));
        cout << unit << setw(width) << fmt.c_str() << endl;
    }
    
    int main()
    {
        double x = 12345678.90;
        while(x > .001) {
            showCurrency(x);
            x /= 10.0;
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 2010-11-06
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多