0

Just like the title : how can i change a string @"$123.4" into a float value 123.4 in iOS

NSString *string = @"$123.4";

Any help will be appreciated. Thanks in advance.

Giki

Giki
  • 11
  • 3
    `float price = [[string substringFromIndex:1] floatValue];`. Also, why the `NSScanner` tag? –  Jul 30 '13 at 06:58
  • 1
    Alternative for memory management freaks: `float price = strtof(string.UTF8String + 1, NULL);` –  Jul 30 '13 at 06:59

2 Answers2

3

@H2CO3 smart answer but i tried this last.

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = @"USD";    
float value = [[formatter numberFromString: @"$123.45"] floatValue];

NSLog(@"%f",value);
Buntylm
  • 7,345
  • 1
  • 31
  • 51
  • this works good, but @user2277872 trick will fail if there is space or something in index 0 ( e.g. NSString *string = @" $123.4";) so +1 to you bit-whacker – Suryakant Sharma Jul 30 '13 at 07:08
  • @SuryakantSharma Correct, 1 white Space can change the result. – Buntylm Jul 30 '13 at 07:28
  • @SuryakantSharma, I wasn't giving the answer, I was relaying the answer from the comment under the question because it seemed to be a good answer. – user2277872 Jul 30 '13 at 08:31
  • ok @user2277872 I wasn't saying you are wrong but that line of code seems failing for some cases that's what I just pointed out. So cheers man. – Suryakant Sharma Jul 30 '13 at 08:35
  • oh, no i understand what you're saying :) i Just wanted to make sure you didn't think I wrote it cuz i had the link for @H2C03 on it. – user2277872 Jul 30 '13 at 09:30
  • @user2277872 as i also mentioned that Good Idea, and my point everyone here bcoz of learn something new as i learned from your answered so and you also good as you gave final touch. so good luck. – Buntylm Jul 30 '13 at 09:33
  • guys. You're so awesome. Thanks for all your solutions.\n and i tried this:NSString *string = @"¥123.4"; NSString *newString = [string stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""]; NSLog(@"floatString:%.1f",newString.floatValue); – Giki Aug 01 '13 at 11:51
  • @Giki nice but what if `NSString *string = @" ¥123.4";` white space before `¥` ? – Buntylm Aug 01 '13 at 11:55
1

As seen with @H2C03

float price = [[string substringFromIndex:1] floatValue];

Hope this helps!

user2277872
  • 2,963
  • 1
  • 21
  • 22