I have an UITextField where the user enters currency value like $1,234.56. In an iPhone app, how can I convert that value to float?
Asked
Active
Viewed 286 times
0
-
possible duplicate of [Re-Apply currency formatting to a UITextField on a change event](http://stackoverflow.com/questions/2388448/re-apply-currency-formatting-to-a-uitextfield-on-a-change-event) – PengOne Sep 10 '11 at 19:31
-
1Do not use a float for money. Either use NSDecimal or an integer multiplied (scaled) by 100. Eventually there will be an arithmetic operation on the value that will cause rounding errors. – zaph Sep 10 '11 at 19:32
-
possible duplicate of [String to float in objective c](http://stackoverflow.com/questions/4831188/string-to-float-in-objective-c) or [Convert currency formatted text to double value](http://stackoverflow.com/questions/7343785/how-to-convert-currency-formatted-text-to-double-value-or-nsnumber-value) – jscs Sep 10 '11 at 21:44
1 Answers
0
You want to use an NSNumberFormatter
to go back and forth between a value 1234.56
and a string @"$1,234.56"
.
Apple has a very good Data Formatting Guide to walk you through setting up and using a currency formatter.
In order to integrate this with a UITextField, you will want to use the delegate method
– textField:shouldChangeCharactersInRange:replacementString:
This allows you to validate and update characters as the user types them in. For an example of how to implement this, look at this post: Re-Apply currency formatting to a UITextField on a change event