views:

71

answers:

2

Say I have a string which is £23.56 or $23.56 how can I convert it into -23.56 ?

I have this part

NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
[strAmount replaceCharactersInRange: [strAmount rangeOfString: strCurrencySymbol]  withString:@""];
A: 

That looks like a good start. You could use rangeOfCharacterFromSet:instead of rangeOfString: though after creating a set of currency symbols. Your code could look like this:

NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
NSCharacterSet *currencySet = [NSCharacterSet characterSetWithCharactersInString:@"$€£"];
[strAmount replaceCharactersInRange: [strAmount rangeOfCharacterFromSet:currencySet]  withString:@"-"];
Toastor
A: 

Use NSNumberFormatter

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLenient:YES];

NSNumber *number = [formatter numberFromString:@"£23.56"];

NSDecimalNumber *minusOne = [NSDecimalNumber decimalNumberWithString:@"-1.00"];
NSDecimalNumber *money = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];
NSDecimalNumber *negativeMoney = [money decimalNumberByMultiplyingBy:minusOne];

NSLog(@"£23.56 is now %@", [negativeMoney description]);
falconcreek
I'm getting a warning on that...warning: 'NSDecimalNumber' may not respond to '-descriptionWithLocale'Also an error -[NSDecimalNumber descriptionWithLocale]: unrecognized selector sent to instance 0x595cde0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSDecimalNumber descriptionWithLocale]: unrecognized selector sent to instance 0x595cde0'terminate called after throwing an instance of 'NSException'
Jules
sorry about that. last statement is updated to use just `description`
falconcreek