jovany
jovany

Reputation:

conversion to doubleValue doesn't work .. but to integerValue does

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?

Upvotes: 0

Views: 1367

Answers (1)

Philipp
Philipp

Reputation: 49802

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;
}

Upvotes: 1

Related Questions