没有符号的NSNumberFormatter货币? [英] NSNumberFormatter Currency Without Symbol?
问题描述
我正在使用NSNumberFormatter从字符串中获取货币值并且效果很好。
I am using NSNumberFormatter to get a currency value from a string and it works well.
我使用此代码执行此操作:
I use this code to do so:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *price = [nf stringFromNumber:[NSNumber numberWithFloat:[textField.text floatValue]]];
但是,它总是在字符串的开头给我一个货币符号。我不是手动形成我的给定字符串,而是不能让格式化程序不给字符串任何货币符号吗?
However, it always gives me a currency symbol at the start of the string. Rather than doing it manually form my given string, can I not somehow have the formatter not give the string any currency symbol?
感谢任何帮助,谢谢。
推荐答案
是的,在设置样式后,您可以调整特定方面:
Yes, after you set the style, you can tweak specific aspects:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterCurrencyStyle];
[nf setCurrencySymbol:@""]; // <-- this
NSDecimalNumber* number = [NSDecimalNumber decimalNumberWithString:[textField text]];
NSString *price = [nf stringFromNumber:number];
正如一些建议,您应该使用数字格式化程序来读取字符串值,尤其是用户正在输入它(根据您的代码建议)。在这种情况下,如果用户输入特定于语言环境的格式化文本,则通用 -floatValue
和 -doubleValue
类型方法获胜不给你截断的数字。此外,您应该使用 -doubleValue
从用户输入的文本(即货币)转换为浮点数。关于国际化的WWDC'12开发者会议视频中有关于此的更多信息。
Just as some advice, you should probably use a number formatter to read the string value, especially if a user is entering it (as suggested by your code). In this case, if the user enters locale-specific formatting text, the generic -floatValue
and -doubleValue
type methods won't give you truncated numbers. Also, you should probably use -doubleValue
to convert to a floating point number from user-entered text that's a currency. There's more information about this in the WWDC'12 developer session video on internationalization.
编辑:使用 NSDecimalNumber
在示例代码中表示用户输入的数字。它仍然没有进行适当的验证,但比原始代码更好。感谢 @Mark !
Used an NSDecimalNumber
in the example code to represent the number the user enters. It's still not doing proper validation, but better than the original code. Thanks @Mark!
这篇关于没有符号的NSNumberFormatter货币?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!