Converting NSDecimalNumber to NSString

22,214

Solution 1

You need to use the stringWithFormat function:

NSString *typeId = [NSString stringWithFormat:@"%@", [obj objectForKey:@"TypeID"]];

or stringValue:

NSString *typeId = [[obj objectForKey:@"TypeID"] stringValue];

Solution 2

This should work:

NSString *typeId = [[obj objectForKey:@"TypeID"] stringValue];

Solution 3

If you want to get string value, just use "description". It works fine even if returned type is NSDecimalNumber, or NSString, or whatever:

NSString *typeId = [[obj objectForKey:@"TypeID"] description];

Solution 4

Since this is the top search result and I don't see a question for NSDecimalNumber to String in Swift, here it is. This will show the localized decimal separator and all decimal places with a non-zero value.

let string = decimalNumber.description(withLocale: Locale.current)

Share:
22,214
4thSpace
Author by

4thSpace

Updated on January 11, 2020

Comments

  • 4thSpace
    4thSpace over 4 years

    I'm retrieving a key from an object that looks like this:

    po obj
    {
      TypeID = 3;
      TypeName = Asset;
    }
    

    The key value is being retrieved like this:

    NSString *typeId = (NSString*)[obj objectForKey:@"TypeID"];
    

    Rather than typeId being an NSString, it is an NSDecimalNumber. Why is that?

    How do I convert it to an NSString?

  • axiixc
    axiixc about 10 years
    You can't just cast an NSString to an NSDecimalNumber, they are different type's and you'll crash if you try to use NSDecimalNumber methods on that pointer.