0

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];
}
cory ginsberg
  • 2,907
  • 6
  • 25
  • 37

1 Answers1

1

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

Community
  • 1
  • 1
Sebastian
  • 7,670
  • 5
  • 38
  • 50