在 NSString 中填充数字
我有一个 int,例如 45。我想从这个 int 中获取 NSString,并用 4 个零填充。因此结果将是:@"0045"
。类似地,如果int是9,我想得到:@"0009"
。
我知道我可以计算位数,然后从我想要填充的零数量中减去它,并将该数字添加到字符串中,但是有没有更优雅的方法?谢谢。
I have an int, for example say 45. I want to get NSString from this int padded with 4 zeroes. So the result would be : @"0045"
. Similar, if the int is 9, I want to get: @"0009"
.
I know I can count the number of digits, then subtract it from how many zeroes i want padded, and prepend that number to the string, but is there a more elegant way? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
获得填充数字。
如果它有效,那么您可以通过更新
如果您想要任意数字,则必须为您的格式创建一个格式:
更新2
请参阅 @Ibmurai 关于如何使用 NSLog 正确填充数字的评论。
Try this:
If it works, then you can get padded number with
Update
If you want to have arbitrary number you'd have to create a format for your format:
Update 2
Please see @Ibmurai's comment on how to properly pad a number with NSLog.
抱歉,我用已经接受的答案来回答这个问题,但答案(在更新中)不是最好的解决方案。
如果您想要任意数字,您不必必须为您的格式创建格式,如IEEE printf 支持此功能。相反,这样做:
虽然其他解决方案有效,但它的效率和优雅性较差。
来自 IEEE printf 规范:
Excuse me for answering this question with an already accepted answer, but the answer (in the update) is not the best solution.
If you want to have an arbitrary number you don't have to create a format for your format, as IEEE printf supports this. Instead do:
While the other solution works, it is less effective and elegant.
From the IEEE printf specification:
Swift 版本作为 Int 扩展(人们可能想为该方法想出一个更好的名称):
示例:
Swift version as Int extension (one might wanna come up with a better name for that method):
Examples: