joachim joachim - 2 months ago 10
C++ Question

Reading fixed doubles with fixed point from file and convert into long

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?

Answer

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?