将 UITextField 格式化为价格 (XXX,XXX.XX)
我一直在绞尽脑汁试图找到解决这个问题的办法。
我只是希望 UITextField 将输入的数字正确格式化为价格。这意味着只允许使用一个小数点、小数点后两位数字(如果输入的话)以及用于分隔大数字(例如 150,000)的“,”。
这就是价格的正确格式,那么为什么正确格式如此困难呢?
我最接近的解决方案是 此代码。然而,它的问题是,输入四位数字后,它会恢复为 0?这接近解决方案,我只是不明白为什么它会做出这种奇怪的行为。
I've been tearing my hair out trying to find a solution to this.
I simply want a UITextField to correctly format an inputted number as a price. That means only a single decimal point is allowed, two digits after the point (if they were typed in) and a ',' to separate large numbers (eg 150,000).
That is how a price is properly formatted, so why is it so difficult to get right?
The closest I've come to a solution is this code. The problem with it, however, is after typing in four digits it reverts to 0?? This is close to a solution, I just can't understand why it does this strange behavior.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上您不需要任何代码。只需将数字格式化程序拖到 nib 文件中的文本字段上,并将其配置为使用“货币”样式即可。
通过代码,这将是
[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]
请注意,价格的格式因区域设置而异。例如,在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定格式可以为您解决这些差异。
You actually don't need any code for this. Just drag a number formatter on your text field in the nib file and configure it to use the "Currency" style.
Via code this would be
[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]
Beware that the format of prices is very different depending on the locale. In Germany for example, the dot is used as a thousands separator and the comma as the decimal point. Using a style instead of a fixed format takes care of those differences for you.
嗨这是我的解决方案。
ViewController 代码
ViewDidLoad
ViewController 中的 UITextFieldDelegate
就是这样
Hi Here is my solution.
ViewController Code
ViewDidLoad
UITextFieldDelegate in Your ViewController
That's It