Velocity Reviews > C++ > How to check if a double is near an int?

# How to check if a double is near an int?

Thomas J. Gritzan
Guest
Posts: n/a

 04-24-2008
xz wrote:
>> Given:
>> #include <cmath>
>> const double eps = 0.0001; // your treshold
>> double d = 10.00005; // your number
>>
>> The algorithm would be:
>> 1. Round d to nearest integer.
>> 2. Check if nearest integer is within treshold.
>>
>> double near = std::floor(d+0.5);
>> if (std::abs(d - near) < eps) {

>
> I guess you meant fabs(...), right?

No. std::abs is overloaded for built-in types. fabs() has the signature:
double fabs(double);

So in this case you can use both.

--
Thomas

xz
Guest
Posts: n/a

 04-24-2008
On Apr 23, 9:59*pm, "Thomas J. Gritzan" <(E-Mail Removed)>
wrote:
> xz wrote:
> >> Given:
> >> #include <cmath>
> >> const double eps = 0.0001; // your treshold
> >> double d = 10.00005; // your number

>
> >> The algorithm would be:
> >> * *1. Round d to nearest integer.
> >> * *2. Check if nearest integer is within treshold.

>
> >> double near = std::floor(d+0.5);
> >> if (std::abs(d - near) < eps) {

>
> > I guess you meant fabs(...), right?

>
> No. std::abs is overloaded for built-in types. fabs() has the signature:
> * *double fabs(double);
>
> So in this case you can use both.

Thanks!

>
> --
> Thomas