Alex Rivera | Logout

How to convert string with number to NSDecimalNumber that has a comma not a decimal point?

Asked 2010-11-01T01:17:25.783
14

I have an interface giving me numbers like this 0000000012345,78

So i figured out how to make a number out of them. But I need to calculate with that number and what I actually need is a decimal number.

NSNumberFormatter *fmtn = [[NSNumberFormatter alloc] init];
[fmtn setFormatterBehavior:NSNumberFormatterBehavior10_4];
[fmtn setNumberStyle:NSNumberFormatterDecimalStyle];
[fmtn setDecimalSeparator:@","];
NSNumber *test = [fmtn numberFromString:@"0000000012345,78"];

How can I make my NSNumber to a NSDecimalNumber?

EDIT: This is the code I ended up with:

NSDictionary *localeDict = [NSDictionary dictionaryWithObject:@"," forKey:@"NSDecimalSeparator"];
NSDecimalNumber *test = [[NSDecimalNumber alloc] initWithString:@"00000000012345,78" locale:localeDict];

How to put together the locale dictionary could not be described as "well documented" and it took me some googling to find an example.

This one also worked:

NSLocale *deLoc = [[NSLocale alloc] initWithLocaleIdentifier:@"de"];
NSDecimalNumber *testd = [NSDecimalNumber decimalNumberWithString:@"00000000012345,78" locale:deLoc];
Edit
Report

1 Answer

1
[NSDecimalNumber decimalNumberWithString:@"0000000012345,78"];

Use caution about the locale, though; if you run that code on an iPhone whose region format is not set to French, it might not return what you expect. So you might want to use:

+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString locale:(NSDictionary *)locale

instead.

answered 2010-11-01T01:35:23.933

Your Answer