2012-12-04 125 views
2

我有一個函數,它接受一個double並將其作爲帶有千分隔符的字符串返回。你可以在這裏看到:c++: Format number with commas?C++:如何使用美元符號將貨幣格式化爲貨幣?

#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」,所以在負數的情況下, 。

+2

使用貨幣,你可能會考慮['std :: put_money'](http://en.cppreference.com/w/cpp/io/manip/put_money)。 – chris

+0

@chris - 'std :: money_put'。 –

回答

4
if(value < 0){ 
    ss << "-$" << std::fixed << -value; 
} else { 
    ss << "$" << std::fixed << value; 
} 
+0

其實我比我的解決方案更喜歡它。 – ypnos

2

我認爲你唯一可以做的事情有

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

你需要一個特定的地區與千個分隔符來打印。

1

下面是一個示例程序,用於瞭解格式化從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; 
}