I want to convert a string for example
NSString *stringWithNumber = @"3/4"
into a NSNumber
.
How is this possible?
I want to convert a string for example
NSString *stringWithNumber = @"3/4"
into a NSNumber
.
How is this possible?
You can use an NSEXpression
to "calculate" the value. Note that you will have the regular int division problem with "3/4".
NSExpression *expression = [NSExpression expressionWithFormat:@"3.0/4.0"];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
If you are only working with n/m
fractions, and you mean to have a number representing the result of the fraction, you can do something like
NSString *fraction = @"3/4";
NSArray *components = [fraction componentsSeparatedByString:@"/"];
float numerator = [components[0] floatValue];
float denominator = [components[1] floatValue];
NSNumber *result = @(numerator/denominator);
NSLog(@"%@", result); // => 0.75
Of course this can easily break in case of malformed strings, so you may want to check the format before performing the above computation.
NOTE
In case the fractions coming in input have a format compatible with native float division, David's answer is definitely sleeker and less clunky than mine. Although if you have an input like @"3/4"
, it won't work as expected and you definitely need to do something like I suggested above.
Bottom line, you should specify better your requirements.