我想用C++格式化价格
我可以使用,std::put_money但问题是我的数字格式区域设置与我的货币区域设置不同.
假设我想用法语格式化GBP的价格,如果我将语言环境设置为法语,我会得到一个欧元符号.我需要用户区域设置中的小数和价格区域设置中的货币.
我可以在Java中使用NumberFormat来自十进制语言环境,然后设置我想要的货币.
这可以用C++完成吗?
您可以创建自己的moneypunct构面,继承自std::moneypunct,并使用它构建语言环境。这是您可以从两个语言环境名称构建的方面。一个负责货币符号,另一个负责其他所有内容。
template <class CharT, bool International = false>
class my_moneypunct;
template <class CharT, bool International = false>
class my_moneypunct_byname : public std::moneypunct_byname<CharT, International>
{
friend class my_moneypunct<CharT, International>;
using std::moneypunct_byname<CharT, International>::moneypunct_byname;
};
template <class CharT, bool International>
class my_moneypunct : public std::moneypunct_byname<CharT, International>
{
my_moneypunct_byname<CharT, International> other_moneypunct;
public:
explicit my_moneypunct(const char* myName, const char* otherName, std::size_t refs = 0) :
std::moneypunct_byname<CharT, International>(myName, refs), other_moneypunct(otherName, refs) {}
typename std::moneypunct_byname<CharT, International>::string_type do_curr_symbol() const override {
return other_moneypunct.do_curr_symbol();
}
virtual ~my_moneypunct() = default;
};
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它:
std::moneypunct<char>* mp = new_moneypunct<char>("en_GB.UTF-8", "fr_FR.UTF-8");
// or std::moneypunct<char>* mp = new_moneypunct<char>("fr_FR.UTF-8", "en_GB.UTF-8");
std::locale newloc(std::locale(), mp);
std::cout.imbue(newloc);
std::cout << std::showbase << std::put_money("1234567");
// prints '€12,345.67' or '12 345,67 £'
Run Code Online (Sandbox Code Playgroud)
请注意,这未针对内存泄漏进行测试。
您还可以,而不是继承std::moneypunct_byname,只继承std::moneypunct并将每个可覆盖的方法转发到moneypunct您使用std::use_facet. 或硬编码您的货币符号,或您喜欢的任何其他方式。