这些货币操纵者似乎几乎没有文件记录。我试图通过反复试验来解决这个问题。考虑示例程序:
class CAccountingMoneyPunctFacet : public std::moneypunct<char>
{
protected:
virtual string_type do_curr_symbol() const {return ")";}
virtual char_type do_thousands_sep() const {return ',';}
virtual char_type do_decimal_point() const {return '.';}
virtual string_type do_positive_sign() const {return "";}
virtual string_type do_negative_sign() const {return "(";}
virtual string_type do_grouping() const {return "\03";}
virtual int do_frac_digits() const {return 2;}
virtual pattern do_pos_format() const
{
pattern p;
p.field[0] = value;
p.field[1] = none;
p.field[2] = none;
p.field[3] = none;
return p;
}
virtual pattern do_neg_format() const
{
pattern p;
p.field[0] = sign;
p.field[1] = value;
p.field[2] = symbol; // Very retarded C++ standard need to do this kind of a hack for negative numbers!
p.field[3] = none;
return p;
}
};
int main(int argc,char* argv[])
{
std::ostringstream oss;
oss.imbue(std::locale(std::locale(),new CAccountingMoneyPunctFacet));
oss << std::put_money(1234567.23) << std::endl;
// << (-1234567) << " " << std::setiosflags(std::ios_base::showbase) << std::put_money(-12345678911.314159) << std::endl;
std::cerr << oss.str();
return 0;
}
此代码的问题在于它打印出12,345.67。这是非常糟糕的,因为它不仅丢失了现在关闭的小数100倍。我看看MSVC ++ STL实现并且非常困惑:
virtual _OutIt __CLR_OR_THIS_CALL do_put(_OutIt _Dest,
bool _Intl, ios_base& _Iosbase, _Elem _Fill,
long double _Val) const
{ // put long double to _Dest
bool _Negative = false;
if (_Val < 0)
_Negative = true, _Val = -_Val;
size_t _Exp;
for (_Exp = 0; 1e35 <= _Val && _Exp < 5000; _Exp += 10)
_Val /= 1e10; // drop 10 zeros before decimal point
string_type _Val2;
char _Buf[40];
**int _Count = _CSTD sprintf_s(_Buf, sizeof (_Buf), "%.0Lf",**
_Val); // convert to chars
for (int _Off = 0; _Off < _Count; ++_Off)
_Val2.append((typename string_type::size_type)1,
_MAKLOCCHR(_Elem, _Buf[_Off], _Cvt)); // convert chars
_Val2.append(_Exp,
_MAKLOCCHR(_Elem, '0', _Cvt)); // scale by trailing zeros
return (_Putmfld(_Dest, _Intl, _Iosbase, _Fill, _Negative, _Val2));
}
观察带有double的函数,但有一个sprintf,它会删除所有小数。在我再次重新发明轮子之前,我想在这里得到C ++专家的意见。
答案 0 :(得分:3)
这些都是C ++标准的直接要求:
§22.4.6.2.2[locale.money.put.virtuals] / 1
参数单位被转换为宽字符序列,就像
ct.widen(buf1, buf1 + sprintf(buf1, "%.0Lf", units), buf2)
[...]模式一样mp.pos_format()
的结果。
此处,mp
是std::moneypunct
方面,因此,继续其要求,
§22.4.6.3[locale.moneypunct] / 3
小数点后所需的位数(如果有)正好是
frac_digits()
返回的值。
最后, §22.4.6.3.2[locale.moneypunct.virtuals] / 6
int do_frac_digits() const;
返回:十进制基数分隔符后的位数(如果有)。 [261]261)在美国常见的语言环境中,这是2。
所有这些确实可以归结为“put_money
的论点是以美分”