Converting currency text values (like $1234.56) to float
I have an U开发者_StackOverflow社区ITextField where the user enters currency value like $1,234.56. In an iPhone app, how can I convert that value to float?
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
精彩评论