Reputation: 5823
As title states, if I have a float, I need to get the fraction part as an integer, how do I do it?
I was thinking:
is there any better/smarter way?
update:
I forgot to mention, the float has format like: X.YZ so there are at most two digits after decimal point.
Upvotes: 2
Views: 6590
Reputation: 39988
NSString *str = [NSString stringWithFormat:@"%f", value];
NSArray *arr = [str componentsSeparatedByString:@"."];
int num = [[arr objectAtIndex:1] intValue];
Upvotes: 4
Reputation: 7079
Here's my solution:
float value = 12.345f;
float integral;
float divisor = 1000.0f;
float fractional = modff(value, &integral); // breaks a float into fractional and integral parts
int xyz = (int)fmodf(fractional*divisor, divisor); // modulo (cannot just use %)
NSLog(@"XYZ: %d", xyz); // logs "XYZ: 345"
By changing the value of divisor
you can get the precision you want, e.g. only XY (100.0f) or X (10.0f).
The solution is not the most performant, but useful. I think it could be optimized using bitwise operations.
Notes on using "f":
Upvotes: 0
Reputation: 3907
You use the modf function:
double integral;
double fractional = modf(some_double, &integral);
refer this fractional part of NSDecimalnumber
Upvotes: 9
Reputation: 987
float temp=12.123;
NSString *str=[NSString stringWithFormat:@"%f",temp];
NSArray *arr=[str componentsSeparatedByString:@"."];
int tempInt=[[arr lastObject] intValue];
Upvotes: 5
Reputation: 17186
Float never represents a number with accuracy. The best way is to create a string from "double" number and then do the string manipulation to get the digits after decimal point.
Upvotes: 0
Reputation: 1336
How about taking the float and multiply by 1000 and convert the result to an integer?
Upvotes: 1
Reputation: 135
Let take a example: x = 129.567;
convert x into integer and put in y. y = int(x); so y = 129;
now subtract y from x. so z = x-y; z = .567
z = z*1000; so z = 567
I think thats what you are looking for.
Upvotes: 2