2

I'm calculating the percentage of a number like so:

CGFloat total = 9;
CGFloat onePercent = total / 100;

CGFloat otherNum = 2;
CGFloat otherNumPercentage = otherNum / onePercent;

The result should be 22.2 repeating. However, it returns +Inf, which I believe is infinity.

I didn't think it would be treated as infinity as 22-23 certainly doesn't count for infinity, however is it because of the forever recurring .2?

Not sure how to handle this, how can I get my expected result?

Community
  • 1
  • 1
Josh Kahane
  • 16,765
  • 45
  • 140
  • 253
  • 1
    Is your code written exactly as above? Are you sure none of those numbers are integers? – James P Jan 13 '16 at 14:43
  • 2
    When you use constant numbers i.e. `9`, I had always assumed you needed to specify `9.0f` to indicate its a `float` rather than an `int`? – Flexicoder Jan 13 '16 at 14:45
  • @Flexicoder that was it! Strange that we should have to cast it directly as an float as you specify, but that did resolve the issue. Thank you both for your input. Feel free to leave it as an answer and I'll give it a tick! – Josh Kahane Jan 13 '16 at 14:47
  • I'm not sure that's correct, according to this it should be a double. http://stackoverflow.com/a/15405182/488611 – James P Jan 13 '16 at 14:54
  • 1
    Your code above should work if total is a float. If total was an integer then it would not give the desired result because `total/100` would be done using integer math, yielding a zero, and then the zero would be converted to a float and stored in `onePercent`. – Duncan C Jan 13 '16 at 14:54
  • @JoshKahane a few extra reputation points are always useful – Flexicoder Jan 13 '16 at 14:54

1 Answers1

2

When you use constant numbers i.e. 9 you need to specify 9.0f to indicate its a float rather than an int

Flexicoder
  • 8,251
  • 4
  • 42
  • 56
  • 2
    That is only true if the type is otherwise unclear to the compiler, e.g. if it's not part of a variable definition like it's the case here. Also, within arithmetic expressions such as `total / 100`, if `total` is not an `int`, `100` will be cast to `total`s type. – Tobi Nary Jan 13 '16 at 15:35