8

In Objective C, how can I check if value is integer number like 2.000 , 3.000, 8.000 stored as a float, and not a fraction like 2.456, 3.578

6
  • 5
    "a perfect number is a positive integer that is equal to the sum of its proper positive divisors" All you want to know is if it has decimals or not, am I correct? Commented Nov 16, 2013 at 13:11
  • You need to define whether you mean an exact integer (which is possible in IEEE float but not some other float formats) or simply something that appears to be an integer to a given level of precision. Commented Nov 16, 2013 at 13:19
  • @HotLicks I have float number which increases from 0.000 to 12.000. I want to fire action when number is integer like 1.000,2.000 etc. Commented Nov 16, 2013 at 13:35
  • And you increase it in what size increments? Commented Nov 16, 2013 at 13:48
  • 3
    @SourabhKumbhar Adding random fractions which are not exactly representable, such as 0.012, 0.157, 0.587, is very unlikely to result in an exact integer. You should probably allow a range around each integer. Commented Nov 16, 2013 at 14:53

5 Answers 5

24

I think you're asking how to find out if a number stored as a float is an integer. There are a number of techniques. Here's one:

if(fVal == floorf(fVal))
    ... // do something
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for this!! I have been trying for the last two days to achieve this basic functionality and failed (lol).... You are a life saver!!
14

Use the floating point remainder function:

if (fmod(fVal, 1.0) == 0.0)
   // is integer

or

BOOL isInteger = !fmod(fVal, 1.0);

Comments

4

I believe it's the simplest way to check it:

if( fnum == (int)fnum ) {
    //fnum has integer value without decimals
}

Comments

2

I personally like

 #define F_ISWHOLENUM(_float) (!fmod(_float, 1.0f))

Comments

0
float number = myNum.floatValue;
 CFNumberType numberType = CFNumberGetType((CFNumberRef)myNum);
if(number == floorf(number) && (number == 1 || number == 0))
{
    // It is a bool (Exceptions 1.000, 0.00000)
}
else
{
    // It is some other number use numberTyoe here except kCFNumberCharType
    if (numberType == kCFNumberSInt32Type) {

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.