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

hol picture hol · Nov 1, 2010 · Viewed 8.7k times · Source

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

Answer

aeropapa17 picture aeropapa17 · May 10, 2012

To convert an NSNumber to NSDecimalNumber, wouldn't it make more sense to avoid the character representation altogether with this code?

NSNumber* source = ...;

NSDecimalNumber* result = [NSDecimalNumber decimalNumberWithDecimal:[source decimalValue]];