0

I have a Label, let's call it currencyFormattedLabel, the value of which was earlier formatted in another method as currency (with currencyFormatter).

Now, I want to use the number equivalent in that Label. However, when i go to get the number, I only get a value of 0.00.

Maybe this will help explain:

float x = [currencyFormattedLabel.text floatValue];
NSLog(@"x = %.2f", x);

So, if the currencyFormattedLabel is $2.00, this method always ends up returning: x = 0.00 What i want is for it to return x = 2.00.

Is there a way to take my currencyFormattedLabel and get the number value of it?

Thanks for any help you can give!

Matthias Bauch
  • 88,097
  • 19
  • 217
  • 244
Jupiter869
  • 637
  • 2
  • 7
  • 19
  • 1
    What value is returned by currencyFormattedLabel.text? Is it what you expect? – bneely Feb 10 '12 at 19:05
  • hint: NSLog(@"text = %@", currencyFormattedLabel.text); – bneely Feb 10 '12 at 19:06
  • 1
    Also, [don't use floats for money](http://stackoverflow.com/questions/6333711/objective-c-issue-with-rounding-float/6334471#6334471). You should really be getting an integer value that reprents cents instead. – jscs Feb 10 '12 at 19:29
  • @Josh, but then I can't siphon off a fraction of a cent from every transaction and transfer it to my offshore account. ha. (+1 for you) – picciano Feb 10 '12 at 19:49

2 Answers2

1

The dollar sign in the NSString is throwing things off. You will have better luck using NSScanner.

NSScanner *scanner = [NSScanner scannerWithString:currencyFormattedLabel.text];
float x;
[scanner scanFloat: &x];
NSLog(@"x = %.2f", x);
picciano
  • 21,170
  • 9
  • 62
  • 81
  • Thank you so much for this suggestion!! NSScanner is something I've never used before and when I add it to my code, the answer I get no matter what is in my originally currencyFormattedLabel is -2.00. What does the & do in the [scanner scanFLoat: &x]; command do? I suspect that may be the source of it still not working. – Jupiter869 Feb 10 '12 at 20:12
  • The & is just the syntax used for passing in a reference (or address/pointer) to a variable. I doubt that's causing the issue. I would log the NSString to be absolutely sure you have what you think you have. NSLog(@"text = %@", currencyFormattedLabel.text); – picciano Feb 10 '12 at 21:01
0

You could also use:

float x = [[currencyFormattedTextLabel.text substringFromIndex:1] floatValue];

if you knew the number would always be predceeded by a dollar sign.

Jamie
  • 5,060
  • 26
  • 25