如何将具有负整数的NSString转换为负整数

Posted

技术标签:

【中文标题】如何将具有负整数的NSString转换为负整数【英文标题】:How to convert NSString with negative integer into negative integer 【发布时间】:2017-07-26 06:49:10 【问题描述】:

在我的应用程序中,如果 NSString 包含负整数,我想显示 0。我试图将 NSString 转换为有符号整数,但我的 NSString 到有符号整数的转换代码总是返回 0 值。

例如:我想将@"-0.02" 转换为-0.02 int。但我的代码总是返回 0 而不是原始值。

我尝试了以下代码:

    (signed)[@"-0.02" intValue] //返回 0 [[NSNumberFormatter new] numberFromString:timespent] //返回值为 -0.02 的 NSNumber,但在进行 < 0 比较时,我将 NSNumber 转换为 signedIntValue(signed)[[[NSNumberFormatter new] numberFromString:timespent] intValue] //但它返回 0

任何人都知道如何在 ios - Objective-c 中做到这一点?

【问题讨论】:

float numFloat = [@"-0.02" floatValue]; // 返回 -0.02。 你应该尝试使用这个NSString* value = @"-123"; intValueOfString = [value IntergerValue];。而不是 intValue 使用 intergerValue 你应该阅读“整数”(int)在你的语言中的翻译,或者知道它的数学含义。 注意:int 是整数,整数是整数,如 1,2,3,4,5。您不能像您在问题中指定的那样使用 -0.02 int,因为 -0.02 是浮点数而不是 int。 【参考方案1】:

您必须使用double 而不是int

您的字符串值是double 而不是integer

   NSString *numberString = @"-0.02";

   double value = [numberString doubleValue];
   NSLog(@"%.2f", value);  //-0.02

【讨论】:

我认为 double d = [numberString doubleValue];更好。 使用 double 更好,否则另一种方式使用 containsstring 概念作为句柄

以上是关于如何将具有负整数的NSString转换为负整数的主要内容,如果未能解决你的问题,请参考以下文章