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];
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]];
If you check out the NSDecimal Class Reference, you'll see you can create new NSDecimalNumber
s from NSString
s (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).
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With