【发布时间】:2016-10-02 20:41:36
【问题描述】:
我正在从文件中读取美元价格。示例
asset_jsld 40.54
asset_sxd 40.80
我想要一个map,以这些价格为关键字。由于float 或double 不是理想的键,我将我的值转换为美元美分并将它们存储为long。 words 是 string 按原始文件列的列表。
using boost::spirit::qi::parse;
// ...
if (!parse(words[1].begin(), words[4].end(), double_, price_d))
// Error handeling
long price = boost::numeric_cast<long>(price_d * 100.0);
问题是double 是 40.80 而long 是4079。这个舍入误差是否来自numeric_cast?有数值稳定的替代方案吗?
【问题讨论】:
-
从
double到long的转换趋向于0。因此,要在您的情况下正确舍入,您可以使用long price = boost::numeric_cast<long>(price_d * 100.0 + 0.5)舍入到几乎最接近的值,前提是price_d >= 0。
标签: c++ c++11 boost rounding numeric