Converting NSDecimalNumber to NSString

大兔子大兔子 提交于 2019-12-03 07:11:50

问题


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?


回答1:


You need to use the stringWithFormat function:

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

or stringValue:

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



回答2:


This should work:

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



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



回答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)




回答5:


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;


来源:https://stackoverflow.com/questions/2573611/converting-nsdecimalnumber-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!