2017-07-26 65 views
0

在我的应用程序中,如果NSString包含负整数,我想要显示0。我试图将NSString转换为signed int,但是我的NSString以signed int转换代码始终返回0值。如何将带负整数的NSString转换为负整数

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

我试图与下面的代码:

  1. (signed)[@"-0.02" intValue] //返回0
  2. [[NSNumberFormatter new] numberFromString:timespent] //返回的NSNumber与-0.02值但同时做< 0比较,我转换成NSNumber作为signedIntValue // (signed)[[[NSNumberFormatter new] numberFromString:timespent] intValue]但它返回0

任何人都知道怎么做,在iOS版 - Objective-C的?

+1

float numFloat = [@“ - 0.02”floatValue]; //返回-0.02。 – GeneCode

+0

你应该尝试使用这个'NSString * value = @“ - 123”; intValueOfString = [值IntergerValue];'。 而不是** intValue ** use ** intergerValue ** –

+2

您应该阅读您的语言中的“integer”(int)的翻译,或者了解它的数学含义。 – Larme

回答

3

你必须使用double代替int

您的字符串值double没有integer

NSString *numberString = @"-0.02"; 

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

我想double d = [numberString doubleValue];更好。 – Jack

+0

使用double更好其他方式使用containssstring概念处理 –