Re: How to determine if double contains an integer value?
DeCaf wrote:
Hi,
I'm wondering if there is a "correct" way to check if a double (or any
other floating point type) contains an integer value?
Sorry but what do you mean a double "contains" an integer?
Even you can round a double to a mathematical integer,
it is quite possible that the integer is beyond the
numeric_limits<int>::max() .
I was thinking along the way of:
bool is_integer(double d)
{
return (d - (int)d) == 0.0;
}
Floating point comparison is one issue but if the floating point
types to integral types cast is considered unsafe. If the double
could not be casted into the range of integer, then the
behavior is undefined. IMHO, casting a floating number to integer
is not trivial at all.
But since I'm not too good at floating point arithmetic, I'm not sure
if this would work in 100% of the cases. Does anyone know if this will
always work, or is there a better way of performing this check?
If you are really doing numeric casting, then maybe you should
check Boost::numeric_cast.
For example, Boost::numeric_cast throws correct overflow
exception for following ill-formed code.
#include <boost/numeric/conversion/cast.hpp>
#include <boost/numeric/conversion/converter_policies.hpp>
#include <iostream>
int main()
{
using boost::numeric_cast;
using boost::numeric::bad_numeric_cast;
using boost::numeric::positive_overflow;
using boost::numeric::negative_overflow;
try {
double a = 0.;
double b = 1.;
int i = numeric_cast<int>(b/a);
}
catch(bad_numeric_cast& e) {
std::cout << e.what();
}
return 0;
}
$ ./nc
bad numeric conversion: positive overflow
$
HTH
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]