Struggling with currency in Cocoa.

Posted by Meltemi on Stack Overflow See other posts from Stack Overflow or by Meltemi
Published on 2009-02-27T01:45:22Z Indexed on 2010/05/29 16:02 UTC
Read the original article Hit count: 498

I'm trying to do something I'd think would be fairly simple: Let a user input a dollar amount, store that amount in an NSNumber (NSDecimalNumber?), then display that amount formatted as currency again at some later time.

My trouble is not so much with the setNumberStyle:NSNumberFormatterCurrencyStyle and displaying floats as currency. The trouble is more with how said numberFormatter works with this UITextField. I can find few examples. This thread from November and this one give me some ideas but leaves me with more questions.

I am using the UIKeyboardTypeNumberPad keyboard and understand that I should probably show $0.00 (or whatever local currency format is) in the field upon display then as a user enters numerals to shift the decimal place along:

  • Begin with display $0.00
  • Tap 2 key: display $0.02
  • Tap 5 key: display $0.25
  • Tap 4 key: display $2.54
  • Tap 3 key: display $25.43

Then [numberFormatter numberFromString:textField.text] should give me a value I can store in my NSNumber variable.

Sadly I'm still struggling: Is this really the best/easiest way? If so then maybe someone can help me with the implementation? I feel UITextField may need a delegate responding to every keypress but not sure what, where and how to implement it?! Any sample code? I'd greatly appreciate it! I've searched high and low...

Edit1: So I'm looking into NSFormatter's stringForObjectValue: and the closest thing I can find to what benzado recommends: UITextViewTextDidChangeNotification. Having really tough time finding sample code on either of them...so let me know if you know where to look?

© Stack Overflow or respective owner

Related posts about cocoa

Related posts about cocoa-touch