ios 将 NSDecimalNumber 转换为 NSString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:06:09  来源:igfitidea点击:

Converting NSDecimalNumber to NSString

objective-cioscocoa-touchnsstringnsdecimalnumber

提问by 4thSpace

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?

typeId 不是 NSString,而是 NSDecimalNumber。这是为什么?

How do I convert it to an NSString?

如何将其转换为 NSString?

回答by Jeff B

You need to use the stringWithFormatfunction:

您需要使用该stringWithFormat功能:

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

or stringValue:

stringValue

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

回答by Michael

This should work:

这应该有效:

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

回答by Cao Huu Loc

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

如果您想获取字符串值,只需使用“描述”。即使返回类型是 NSDecimalNumber、NSString 或其他类型,它也能正常工作:

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

回答by blwinters

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.

由于这是最热门的搜索结果,而且我在 Swift 中没有看到 NSDecimalNumber 到 String 的问题,所以在这里。这将显示本地化的小数点分隔符和所有具有非零值的小数位。

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

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

回答by taus-iDeveloper

Use this to convert NSDecimalNumber to NSString:

使用此NSDecimalNumber转换成的NSString:

NSDecimalNumber* dec1;
NSString* str;

str = dec1.stringValue;

Use this to convert NSString to NSDecimalNumber:

用这个来的NSString转换为NSDecimalNumber:

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

dec = (NSDecimalNumber *)string1;