Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether a double has a fractional part?

Tags:

c++

Basically I have two variables:

double halfWidth = Width / 2;
double halfHeight = Height / 2;

As they are being divided by 2, they will either be a whole number or a decimal. How can I check whether they are a whole number or a .5?

like image 784
Split Avatar asked May 14 '13 01:05

Split


2 Answers

You can use modf, this should be sufficient:

 double intpart;

 if( modf( halfWidth, &intpart) == 0 )
 {
 // your code here
 }
like image 51
Shafik Yaghmour Avatar answered Sep 23 '22 02:09

Shafik Yaghmour


First, you need to make sure that you're using double-precision floating-point math:

double halfWidth = Width / 2.0;
double halfHeight = Height / 2.0;

Because one of the operands is a double (namely, 2.0), this will force the compiler to convert Width and Height to doubles before doing the math (assuming they're not already doubles). Once converted, the division will be done in double-precision floating-point. So it will have a decimal, where appropriate.

The next step is to simply check it with modf.

double temp;
if(modf(halfWidth, &temp) != 0)
{
  //Has fractional part.
}
else
{
  //No fractional part.
}
like image 35
Nicol Bolas Avatar answered Sep 22 '22 02:09

Nicol Bolas