vpiotr / decimal_for_cpp

Decimal data type for C++
273 stars 68 forks source link

Error on == operator #30

Closed stef-pellegrino closed 6 years ago

stef-pellegrino commented 6 years ago
  decimal<2> x;

  x = 5.6;

  if (x == 5.6) {
      puts("ok");
  }

I get with vs2012, this error :

error C2678: binary '==' : no operator found which takes a left-hand operand of type 'dec::decimal' (or there is no acceptable conversion)

vpiotr commented 6 years ago

Such a comparison is not valid with both doubles and also with decimal + double. Use decimal_cast instead:

if (x == decimal_cast<2>("5.6")) {
  puts("ok");
}
stef-pellegrino commented 6 years ago

Ok, and code like this ?

bool operator==(double rhs) const {
  return (m_value == RoundPolicy::round(static_cast<double>(DecimalFactor<Prec>::value) * rhs));
}
vpiotr commented 6 years ago

This code is invalid:

You should not store input values for decimal in double form at any phase, as this can cause some hard to track errors. Also "decimal_for_cpp" library is designed in this way so it doesn't perform roundings inside calculations (only during variable initialisation). This way it blocks using it with float/double in expressions which is invalid.

You can also use decimal_cast with double, but I would avoid that if possible. For storing values outside of decimal you can use getUnbiased() / setUnbiased() which is very fast.