Alex Rivera | Logout

NSNumberFormatter Currency Without Symbol?

Asked 2012-09-20T23:36:20.870
23

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?

Edit
Report

1 Answer

67

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];

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.

Edit: 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!

answered 2012-09-20T23:47:40.867

Your Answer