根据区域设置将带有千位分隔符的数字格式化为 NSString 的最简单方法
我似乎找不到一个简单的方法来做到这一点。我真正需要的是:
[NSString stringWithFormat:@"%d doodads", n];
其中 n 是一个整数。因此,对于 1234,我想要这个字符串(在我的语言环境下):
@"1,234 doodads"
谢谢。
I can't seem to find an easy way to do it. The exact thing I need is:
[NSString stringWithFormat:@"%d doodads", n];
Where n is an int. So for 1234 I'd want this string (under my locale):
@"1,234 doodads"
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于 10.6,这是有效的:
并且它可以正确处理本地化。
For 10.6 this works:
And it properly handles localization.
我最近发现了这一行:
或者在 Swift 2 中:
Swift 3/4:
根据问题格式化:
没有 Objective-C 文字格式化:
这是我提出问题时正在寻找的解决方案。自 iOS 2.0 和 OS X 10.0 起可用,记录为返回根据提供的区域设置格式化的数字的字符串版本。
stringValue
甚至被记录为使用此方法,但传递nil
。鉴于这是我的问题并且这最适合我的答案,我很想更改勾选,但这似乎很残酷。 更新我更改了勾选,这个答案是答案。
I have recently discovered this one-liner:
Or in Swift 2:
Swift 3/4:
Formatted per the question:
Formatted without Objective-C literals:
This is the solution I was looking for when I asked the question. Available since iOS 2.0 and OS X 10.0, documented to return a string version of the number formatted as per the locale provided.
stringValue
is even documented to use this method but passingnil
.Seeing as it is my question and this fits my answer best, I am tempted to change the tick, but it seems cruel. Update I changed the tick, this answer is the answer.
下面没有解决区域设置,但这是在数字格式化程序上设置千位分隔符的更好方法(在我看来)。
The below doesn't address the locale, but it is a better way (in my opinion) of setting the thousand separator on the number formatter.
托德·兰塞姆完美地回答了这个问题。
我想补充一点(在单独的评论中,这样我就可以展示一些格式良好的代码),如果您打算定期执行此操作,那么值得创建一个 NSString 辅助类。
因此,您自己创建一个包含以下内容的 NSStringHelper.h:
.. 和一个包含以下内容的 NSStringHelper.m 文件:
这为您提供了在未来项目中重用此代码的完美方法。
很酷,嘿?
再次,对重新发布 Todd 的答案(这正是我正在寻找的答案!)表示歉意,但这是解决问题的好方法,并准备好在未来的 XCode 项目中使用它。
Todd Ransom answered this perfectly.
I would just like to add (in a separate comment, so I can show some nicely formatted code), that if you plan to do this regularly, it's worth creating an NSString helper class.
So, create yourself an NSStringHelper.h containing this:
..and an NSStringHelper.m file containing this:
This gives you the perfect way to reuse this code in future projects.
Cool, hey ?
Again, apologies for reposting Todd's answer (which was exactly what I was looking for !), but this is a great way to solve the problem, and have it ready to be used in your future XCode projects.
使用
NSNumberFormatter
。Use an
NSNumberFormatter
.