【问题标题】:Reading fixed doubles with fixed point from file and convert into long从文件中读取具有固定点的固定双打并转换为长
【发布时间】:2016-10-02 20:41:36
【问题描述】:

我正在从文件中读取美元价格。示例

asset_jsld 40.54
asset_sxd 40.80

我想要一个map,以这些价格为关键字。由于floatdouble 不是理想的键,我将我的值转换为美元美分并将它们存储为longwordsstring 按原始文件列的列表。

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 而long4079。这个舍入误差是否来自numeric_cast?有数值稳定的替代方案吗?

【问题讨论】:

  • doublelong 的转换趋向于0。因此,要在您的情况下正确舍入,您可以使用long price = boost::numeric_cast&lt;long&gt;(price_d * 100.0 + 0.5) 舍入到几乎最接近的值,前提是price_d &gt;= 0

标签: c++ c++11 boost rounding numeric


【解决方案1】:

如果您想保持一致性,请不要对浮点数进行数学运算。将值读取为字符串,删除点并将其解析为 long

Is floating point math broken?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多