How to check if a double fractional part?

I basically have two variables:

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

Since they are divisible by 2, they will be either an integer or decimal. How can I check if they are an integer or .5?

+6
source share
2 answers

You can use modf , this should be enough:

  double intpart; if( modf( halfWidth, &intpart) == 0 ) { // your code here } 
+13
source

First, you need to make sure that you use double precision floating point math:

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

Since one of the operands is double (namely 2.0 ), this will cause the compiler to convert Width and Height to doubles before doing the math (if they are not double s yet). After conversion, the division will be performed with floating point with double precision. Thus, it will have a decimal value, if necessary.

The next step is to simply check it with modf .

 double temp; if(modf(halfWidth, &temp) != 0) { //Has fractional part. } else { //No fractional part. } 
+1
source

Source: https://habr.com/ru/post/944941/


All Articles