hol
hol

Reputation: 8423

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

Upvotes: 14

Views: 8942

Answers (3)

aeropapa17
aeropapa17

Reputation: 499

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

Upvotes: 39

marcprux
marcprux

Reputation: 10385

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

Upvotes: 1

Itai Ferber
Itai Ferber

Reputation: 29928

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

Upvotes: 1

Related Questions