hzxu
hzxu

Reputation: 5823

Objective-C: how to get 123 from 0.123 or generically xyz... from 0.xyz...?

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:

  1. get index(position) of decimal point
  2. then I can know how many digits after decimal point
  3. get those digits as substring
  4. convert it to an integer

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

Answers (8)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

NSString *str = [NSString stringWithFormat:@"%f", value];
NSArray *arr = [str componentsSeparatedByString:@"."];
int num = [[arr objectAtIndex:1] intValue];

Upvotes: 4

matm
matm

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

Hector
Hector

Reputation: 3907

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

refer this fractional part of NSDecimalnumber

Upvotes: 9

Nikunj
Nikunj

Reputation: 987

 float temp=12.123;
NSString *str=[NSString stringWithFormat:@"%f",temp];
NSArray *arr=[str componentsSeparatedByString:@"."];
int tempInt=[[arr lastObject] intValue];

Upvotes: 5

Apurv
Apurv

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

Tommy Hui
Tommy Hui

Reputation: 1336

How about taking the float and multiply by 1000 and convert the result to an integer?

Upvotes: 1

Rahul Bhansali
Rahul Bhansali

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

Julien
Julien

Reputation: 3477

Take a look at NSDecimalNumber and NSDecimal.

Upvotes: 0

Related Questions