0

I am making an IOS calculator app. I want to get if the division of two numbers will give a floating value or an int value. Can any body tell me how to get this?

Thanks.

NiKKi
  • 3,296
  • 3
  • 29
  • 39

2 Answers2

2

if you want to know without actually computing a/b, check whether the remainder of a/b is null:

if (fmod(a,b) == 0) {
  // integer result
} else {
  // floating-point result
}

see http://www.cplusplus.com/reference/cmath/fmod/

Stéphane
  • 6,920
  • 2
  • 43
  • 53
1

If the floor() of a number is equal to that number, it is an integer.

However, beware of floating-point gotchas.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 2
    This method tests a single number, presumably the quotient. This means the quotient has already been calculated, which means the exact mathematical quotient has been rounded to floating-point, and you have lost information. The calculated result might be an integer even though the exact result is not. The accepted answer by Stéphane does not have this problem. – Eric Postpischil Feb 02 '13 at 23:04
  • I agree, the accepted answer is _better_ than mine, though `fmod`'s arguments are floats as well, so there's no completely escaping the limitations of floating point. – Matt Ball Feb 03 '13 at 00:44
  • For example, with double a=0.5,b=0.1; double c=a/b; c is 5.0 and floor(c)==c, though fmod(0.5,0.1) gives something near 0.1, not 0 (A decent libm shall provide a fmod which answer nearest floating point value). Both answers could match, it all depends if question was about exact division or floating point division... – aka.nice Jun 07 '13 at 21:28