tags:

views:

43

answers:

1

Hello all I'm trying to convert a string to a double and it doesn't work. However if I convert it to an integer it does work

this is my code snippet

int myDuration = [myDurationString integerValue];
int conversionMinute = myDuration / 60;

   if( myDuration < 60 )
   {
    [appDelegate.rep1 addObject:[NSString stringWithFormat:@"%d",myDuration]];
    NSLog(@"show numbers %d", myDuration);
   }
   else
   {
    [appDelegate.rep1 addObject:[NSString stringWithFormat:@"%d",conversionMinute]];
    NSLog(@"show numbers %d", conversionMinute);
   }

Now if I try to do

double myDuration = [myDurationString doubleValue];
double conversionMinute = myDuration / 60;

then it doesn't work. It gives me an output of 0.

So the integerconversion works but somehow the double doesn't does anybody have an idea why?

+1  A: 

You need to supply a matching format specifier. Replace every occurence of %d with %f.

%d simply fetches the next 32-bit word from the stack and treats it as a signed integer. Because of the internal representation of the floating point number, this word is zero in quite a few cases, which is why you get 0.

Here is an example that works fine for me (also with other contents of myDurationString):

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString * myDurationString = @"19";
    double myDuration = [myDurationString doubleValue];
    double conversionMinute = myDuration / 60; 
    if( myDuration < 60 )
    {
     NSLog(@"show numbers %f", myDuration);
    }
    else
    {
     NSLog(@"show numbers %f", conversionMinute);
    }
    [pool drain];
    return 0;
}
Philipp
Thank you for your answer unfortunately I already tried to change the format specifier to %f and it didn't work. I indeed got zero , and after the change I got zero again.
jovany
I've added an example that works fine for me.
Philipp
you are correct I had a typo further down in my code ( not the snippet _
jovany