Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];
like image 315
hol Avatar asked Nov 01 '10 01:11

hol


3 Answers

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]]; 
like image 131
aeropapa17 Avatar answered Oct 20 '22 09:10

aeropapa17


If you check out the NSDecimal Class Reference, you'll see you can create new NSDecimalNumbers from NSStrings (with and without a locale), actual numbers, etc.

If you wanted to convert an NSNumber to an NSDecimalNumber, you could do something like this:

NSDictionary *locale = ...;
NSNumber *number = ...;
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:[number descriptionWithLocale:locale] locale:locale];

Of course, you'll have to correctly create the locale, and such, but that's an exercise left up to you (it might be handy to check out the NSNumber Class Reference, the NSLocale Class Reference, and the Locales Programming Guide).

like image 36
Itai Ferber Avatar answered Oct 20 '22 08:10

Itai Ferber


[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.

like image 1
marcprux Avatar answered Oct 20 '22 07:10

marcprux