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?
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With