0

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?

Kirti Nikam
  • 2,166
  • 2
  • 22
  • 43
  • 1
    float numFloat = [@"-0.02" floatValue]; // returns -0.02. – GeneCode Jul 26 '17 at 06:54
  • You should try to use this `NSString* value = @"-123"; intValueOfString = [value IntergerValue];`. Instead of **intValue** use **intergerValue** – Sumeet Mourya Jul 26 '17 at 06:57
  • 2
    You should read the translation of "integer" (int) in your language, or know the mathematics signification of it. – Larme Jul 26 '17 at 06:59
  • 1
    Note: int is an integer and integer is a round number like 1,2,3,4,5. You can not have a -0.02 int as you specified in your question because -0.02 is a float and not an int. – GeneCode Jul 26 '17 at 07:00

1 Answers1

3

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
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Subramanian P
  • 4,365
  • 2
  • 21
  • 25