Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Whole number part of a float :Objective-C

Tags:

c

objective-c

So i have

float x = x + 0.25;

This float will be called every time a click happens

NSLog(@"%f",x);

I want the nslog to only return the whole number portion so like this

  x        return        

 1.25         1
 1.50         1
 3.25         3
 4.75         4

Any ideas?

like image 968
JDanek Avatar asked Oct 23 '11 18:10

JDanek


2 Answers

Converting to int won't work if the floating-point number is outside the range of int.

Printing with "%.0f" doesn't truncate, it rounds, so 4.75 will print as 5.

If your compiler (more accurately, your runtime library) supports them, the trunc(), truncf(), and truncl() functions, declared in <math.h>, do exactly what you want:

printf("%.0f\n", trunc(x));

Those functions are new in C99, so it's possible your compiler doesn't support them. C90 does provide a floor() function; you can use that if you write some special-case code for negative numbers.

like image 103
Keith Thompson Avatar answered Nov 13 '22 14:11

Keith Thompson


You can treat x as an int (cast):

NSLog("%d", (int)x);

Note: this will not round, it will truncate the value, returning only the integer part.

EDIT: please note that this is not a safe way to truncate all possible float values, it will work fine for small values though (those fitting in an int).

like image 21
jv42 Avatar answered Nov 13 '22 13:11

jv42