3

I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.

NSString *stringValue = @"1235";
priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/(double)100.00];

I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.

I have tried:

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue intValue]/(double)100.00];

priceLabel.text = [NSString stringWithFormat:@"%d",[stringValue doubleValue]/100];

but all without success.

Vladimir
  • 170,431
  • 36
  • 387
  • 313
Alex van Rijs
  • 803
  • 5
  • 17
  • 39
  • Checkout this question: http://stackoverflow.com/questions/169925/how-to-do-string-conversions-in-objective-c ... You need to set up a `NSNumberFormatter` to the locale that the user has set in his settings and use this to grab the information from the string. – klaustopher Sep 26 '11 at 12:44

3 Answers3

14

This is how to convert an NSString to a double

double myDouble = [myString doubleValue];
Pang
  • 9,564
  • 146
  • 81
  • 122
Tendulkar
  • 5,550
  • 2
  • 27
  • 53
  • 2
    So strange the question is string to double. Accepted answer doesn't even solve that problem. But this one here does. :) thanks – Houman Oct 30 '13 at 19:22
13

You have to use %f to show float/double value.

then %.2f means 2digits after dot

NSString *stringValue = @"1235";

NSString *str = [NSString stringWithFormat:@"%.2f",[stringValue doubleValue]/(double)100.00];

NSLog(@"str : %@ \n\n",s);

priceLabel.text = str;

OUTPUT:

str : 12.35

  • for instant help http://chat.stackoverflow.com/rooms/682/conversation/do-u-want-instant-help-for-ur-question-or-r-u-new-bee-to-iphone-ipad-develop – Vijay-Apple-Dev.blogspot.com Sep 26 '11 at 16:36
  • 1
    This does not answer the question. The question says 'String to Double'. This solution just converts String to String. The answer below by Tendulkar is the correct answer to the question. – Guy Feb 05 '17 at 07:37
1

I think you have the wrong format string. Where you have:

[NSString stringWithFormat:@"%d", ...];

You should really have:

[NSString stringWithFormat:@"%f", ...];

%d is used for integer values. But you're trying to display a floating point number (%f).

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152