jona jürgen
jona jürgen

Reputation: 1839

Objective-C: extract numeric fraction in string and convert it to a real number

I have got some strings, they look like this: 1/2 pound steak. Now I need to split the string afetr 1/2 and convert 1/2 to a number. It can be that the string contains more spaceses and 1/2 can also be 1/6 or any other number. Anyone got any idea how to split and convert?

Upvotes: 0

Views: 206

Answers (1)

Juan Catalan
Juan Catalan

Reputation: 2309

This should solve the problem:

NSString *input = @"3/4 pounds of sugar";
// trim white space at the beginning and end
input = [input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// define charater set to split
NSCharacterSet *chSet = [NSCharacterSet characterSetWithCharactersInString:@" /"];
// split string into array of strings by charaters '/' and ' '
NSArray *split = [input componentsSeparatedByCharactersInSet:chSet];
// the result of the fraction inside result
double result = [split[0] doubleValue] / [split[1] doubleValue];

Upvotes: 1

Related Questions