redoc01
redoc01

Reputation: 2297

Float not returning the right decimal value

This is the code i have:

int resultInt = [ja.resultCount intValue];
float pages = resultInt / 10;


NSLog(@"%d",resultInt);
NSLog(@"%.2f",pages);

the resultInt comes back from php script with the value 3559 so the pages result should be 355.9 but i get the result as 355.00 which isn't right

Upvotes: 2

Views: 1051

Answers (2)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39978

Use

float pages = resultInt / 10.0f;

int/int is int but int/float or float/int is float


Edited for more explanation

It is important to remember that the resultant value of a mathematical operation is subject to the rules of the receiving variable's data type. The result of a division operation may yield a floating point value. However, if assigned to an integer the fractional part will be lost. Equally important, and less obvious, is the effect of an operation performed on several integers and assigned to a non-integer. In this case, the result is calculated as an integer before being implicitly converted. This means that although the resultant value is assigned to a floating point variable, the fractional part is still truncated unless at least one of the values is explicitly converted first. The following examples illustrate this:

int a = 7;
int b = 3;
int integerResult;
float floatResult;

integerResult = a / b;          // integerResult = 2  (truncated)
floatResult = a / b;            // floatResult = 2.0  (truncated)
floatResult = (float)a / b;     // floatResult = 2.33333325

Upvotes: 1

rckoenes
rckoenes

Reputation: 69449

This has to do with the fact that you're using integer and not float. Tell the variables that you are using that they are floats and you are done.

int resultInt = [ja.resultCount intValue];
float pages = (float)resultInt / 10.f;

Upvotes: 1

Related Questions