iosobjective-cnsstringsignedsigned-integer

How to convert NSString with negative integer into negative integer


In my app, I want to display 0 if NSString contains negative integers. I tried to convert NSString into signed int but my NSString to signed int conversion code always returns 0 value.

Eg: I want to convert @"-0.02" into -0.02 int. But my code always returns 0 instead original value.

I tried with below code:

  1. (signed)[@"-0.02" intValue] //returns 0
  2. [[NSNumberFormatter new] numberFromString:timespent] //returns NSNumber with -0.02 value but while do < 0 comparison, I converted NSNumber into signedIntValue as (signed)[[[NSNumberFormatter new] numberFromString:timespent] intValue] //but it returns 0

Anyone knows how to do that in iOS - Objective-c?


Solution

  • You have to use double instead of int

    You string value is double not integer.

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