将 NSString 格式化为货币,我应该使用 NSNumberFormatter 吗?
我输入了一系列字符串,它们本质上是美元值,但它们没有格式化。
例如,它们看起来像这样:
- -5
- -2.5
- 697.5
- 0
我想将它们格式化为货币,如下所示:
- ($5.00)
- ($2.50)
- $697.50
- $0.00
理想情况下,我也希望将其本地化。我知道我可以使用 NSNumberFormatter 来实现此目的,但这需要我将这些字符串转换为 NSNumbers 并使用我的格式化程序对它们进行格式化,然后将它们从已格式化的 NSNumber 转换回字符串。
有没有办法完全跳过数字转换而只格式化字符串?
I have a series of strings that come in, that are essentially dollar values, but they are unformatted.
So for example they look like this:
- -5
- -2.5
- 697.5
- 0
I want to format these as a currency, like this:
- ($5.00)
- ($2.50)
- $697.50
- $0.00
Ideally, I'd like it to be localized as well. I know I can use NSNumberFormatter to achieve this, but that would involve me converting these strings to NSNumbers and the formatting them with my formatter, only to convert them back to strings from the NSNumber that has been formatted.
Is there a way to skip the number conversion altogether and just format the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从这里的文档来看,它看起来不像。
编辑
还提出了类似的问题:
将 NSString 转换为 Cocoa 中的等值货币的最简单方法
From the documentation here it doesn't look like it.
EDIT
Similar Question was also asked:
Easiest way to convert a NSString to its currency equivalent in Cocoa
是的,您应该将(未格式化的)字符串转换为数字,然后使用 NSNumberFormatter 转换为字符串。
Yes you should convert your (unformatted) strings to numbers and then use NSNumberFormatter to strings.