Thomas Sampson

Extracting data from float

2 Comments

Earlier this week i was presented with the simple problem of checking if floating point number was a whole number. I stumbled upon the useful function modf and thought it was worth a quick post. the modf function requires <stdio.h> and <math.h>, and allows you to separate the integral and fractional part of a floating point number.

Taking the value 5.24f as an example…

  • Integral part = 5
  • Fractional part=0.24

modf is fully documented here but is rather simple. modf takes two arguments, the first is the value you wish to query (in the case above this would be 5.24). The second argument is a pointer to where the integral part should be placed. The return value of the method is the fractal part. Therefore the solution to my original problem (testing if a float is infact an integer value) is as follows…

Solution

int f;

if(modf(myValue,&f)==0)
{

//myValue is a whole number

}

Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

2 thoughts on “Extracting data from float

  1. none standard libraries … πŸ˜›
    use cstdlib and cmath πŸ˜‰

  2. @christopher whiting
    Hey Chris!

    Can you demonstrate a way to solve this problem using the two libraries you mentioned? If you can I would be more than happy to update this.