将整数格式化为两位小数
我向用户呈现一个显示数字键盘的字段,并且只希望他们能够输入数字——没有小数。然而,由于该字段是货币字段,因此我希望该数字始终显示两位小数。您可能在 ATM 机上见过这种类型的界面。
我已经查看了 NSNumberFormatter 文档和使用 [NSString stringWithFormat] 的常规格式,但我不清楚执行此操作的好方法。我正在使用 UIControlEventEditingChanged 事件的选择器在现场监听。我想在该选择器中进行格式化。当我使用 [NSString stringWithFormat: @"%.2f", amount] 时,它总是将 amount 放在小数点左边。我希望它始终是小数部分,直到输入第三位数字,因此如果用户输入 32,则实际金额为 0.32。如果用户输入173,则该值实际上是1.73。如果用户输入 10047,实际值应该是 100.47 等。
有什么建议吗?
谢谢。
I am presenting the user with a field that displays the number keyboard and only want them to be able to enter numbers--no decimals. Since the field is a currency field, however, I want the number to always display with two decimal places. You've probably seen this type of an interface at an ATM.
I've looked at the NSNumberFormatter docs and general formatting using [NSString stringWithFormat], but it's not clear to me a good way to do this. I am listening on the field with a selector for UIControlEventEditingChanged events. It's in that selector I want to do the formatting. When I use [NSString stringWithFormat: @"%.2f", amount], it always places amount to the left of the decimal. I want it to always be the fraction portion until the third digit is entered, so if the user types 32, the actual amount is .32. If the user enters 173, the value is actually 1.73. If the user enters 10047, the actual value should be 100.47 etc.
Any suggestions?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将他们输入的金额视为美分而不是美元。格式化之前将其除以 100。
Treat the amount they're entering as cents instead of dollars. Divide it by 100 before formatting.