1

I am reading US Dollar prices from a file. Example

asset_jsld 40.54
asset_sxd 40.80

I want to have a map that has these prices as a key. Since float or double are less than ideals keys, I am converting my values into Dollar Cents and I am storing them as a long. words is a list of string by column of the original file.

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);

The problem is that the double is 40.80 and the long is 4079. Does this rounding error come from numeric_cast? Is there are numerical stable alternative?

Joachim
  • 3,210
  • 4
  • 28
  • 43
  • conversion from `double` to `long` are towards 0. So to have a correct rounding in your case, you can use `long price = boost::numeric_cast(price_d * 100.0 + 0.5)` to round to almost the nearest, provided that `price_d >= 0`. – Franck Oct 02 '16 at 20:48

1 Answers1

2

Don't do math operations on floating point numbers if you want consistency. Read the values as strings, remove the dot and parse that as long.

Is floating point math broken?

Community
  • 1
  • 1
krzaq
  • 16,240
  • 4
  • 46
  • 61