Reputation: 2897
I'm trying to get this text field in my app to display in scientific notation after 8 characters are entered in (sort of like the built-in Calculator App). I've got everything working right, except when it's supposed to show in scientific notation, it just shows '0.0'.
What is wrong with my code?
NSString *current;
NSString *str = (NSString*)[sender currentTitle]; //sender is in the method header
if([current isEqualToString:@"0"]) {
current = str;
} else if (current.length < 8){
current = [current stringByAppendingString:str];
} else {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterScientificStyle];
current = [formatter stringFromNumber:(NSNumber*)current];
}
Upvotes: 0
Views: 327
Reputation: 7720
You can't just cast an NSString
to an NSNumber
. Use doubleValue
to convert an NSString
to a double:
current = [formatter stringFromNumber:@([current doubleValue])];
Or you can use an NSNumberFormatter
to convert strings to numbers as described in this answer
Upvotes: 1