如何从双精度值获取货币格式?以下代码段适用于整数,而不能用于双精度吗?
#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;
}
最佳答案
像这样:
#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
您可以在这里找到更多信息:
http://www.cplusplus.com/reference/locale/numpunct/
How can I set the comma to be a decimal point?
http://www.umich.edu/~eecs381/handouts/formatting.pdf
关于c++ - 使用双值的货币格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22104371/