Converting NSDecimalNumber to NSString
Asked Answered
N

5

16

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?

Nix answered 4/4, 2010 at 5:0 Comment(0)
U
32

You need to use the stringWithFormat function:

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

or stringValue:

NSString *typeId = [[obj objectForKey:@"TypeID"] stringValue];
Uglify answered 4/4, 2010 at 5:4 Comment(0)
M
4

This should work:

NSString *typeId = [[obj objectForKey:@"TypeID"] stringValue];
Modification answered 4/4, 2010 at 5:5 Comment(0)
G
1

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];
Galina answered 4/5, 2012 at 4:30 Comment(0)
D
1

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)

Dispel answered 11/1, 2017 at 0:11 Comment(0)
B
-1

Use this to convert NSDecimalNumber to NSString:

NSDecimalNumber* dec1;
NSString* str;

str = dec1.stringValue;

Use this to convert NSString to NSDecimalNumber:

NSString* string1 = @"Stack overflow 123";
NSDecimalNumber* dec;

dec = (NSDecimalNumber *)string1;
Bavaria answered 9/4, 2012 at 12:39 Comment(1)
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.Jegger

© 2022 - 2024 — McMap. All rights reserved.