如何将双精度格式转换为货币格式?例如:3.234,12
我有一个用户输入的字符串,该字符串被视为仅包含数字,例如:“3472042”
。
然后,我将此字符串转换为双精度值,但我希望将其格式化为货币值,例如: 3.472,042
就像 Java 中的 DecimalFormat 一样(如果有帮助的话)。
我用 NSNumberFormatter 尝试了一些东西,但没有运气。有人可以帮我吗?
最初使用这个:
NSString *string = txtOtherPower.text; NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:@"•€£¥./:;@#$%&*(){}[]!?\\-|_=+\"`'~^abcdefghijklmnopqrstvwxyz' '"]; string = [[string componentsSeparatedByCharactersInSet:removeCharSet] componentsJoinedByString:@""];
因此唯一可接受的字符是逗号 ","
和数字。 问题是,如果我输入类似 "2,2,2,2,,,,,1,,2"
的内容,那么它不会执行任何操作。 这与我的字符串/数字混淆了。
我需要格式完美的货币值...有什么想法吗?
I have a string input by the user, this is string is treated to have only numbers, such as: "3472042"
.
I then convert this string to a double value, but I want it to be formatted as a money value, like: 3.472,042
Just like DecimalFormat in Java if that helps.
I tried some things with NSNumberFormatter but no luck. Can anyone give me a hand with that?
Used this at first:
NSString *string = txtOtherPower.text; NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:@"•€£¥./:;@#$%&*(){}[]!?\\-|_=+\"`'~^abcdefghijklmnopqrstvwxyz' '"]; string = [[string componentsSeparatedByCharactersInSet:removeCharSet] componentsJoinedByString:@""];
So that the only acceptable characters are comma ","
and numbers.
The problem is if I type something like "2,2,2,2,,,,,1,,2"
then it just won't do anything.
And that messes with my string/number.
I need perfectly formatted money values... Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个
NSNumberFormatter
,将其样式设置为NSNumberFormatterCurrencyStyle
或NSNumberFormatterDecimalStyle
(或者,如果这些样式不适合您,请使用配置它>setPositiveFormat:
、setNegativeFormat:
等),然后使用stringFromNumber:
将数字转换为字符串。有关详细信息,请参阅此类的文档。
Create an
NSNumberFormatter
, set its style toNSNumberFormatterCurrencyStyle
orNSNumberFormatterDecimalStyle
(or, if those styles don't work for you, configure it withsetPositiveFormat:
,setNegativeFormat:
etc.), and then convert the number to a string withstringFromNumber:
.See the documentation for this class for details.