why is floatValue method turning strings into nonsense?

Discussion in 'iOS Programming' started by LoopLoop, Jul 19, 2010.

  1. macrumors newbie

    Joined:
    Apr 30, 2010
    #1
    Hey all,

    A strange problem here, I'm trying to convert real world longitude / latitude coords into points on my app's screen. Some user types in the coordinates as NSStrings (maybe strange but neccessary at the moment...), the app then has to re scale these coordinates to show up as small dot-buttons on the screen. Simple one would think, but getting totally weird results from the [NSString floatValue]; method.

    Here's the code:

    Code:
    -(void) createAllEventsButtons:(id)sender {
    	
    	NSString *XCoordinate1;
    	NSString *YCoordinate1;
    	int j;
    	float xfloat, yfloat, xScaled, yScaled;
    	
    	NSLog(@"Create All Events Buttons");
    	
    	for (j=0; j < allEdinburghData.count; j++) {
    		
    		XCoordinate1 = [[allEdinburghData objectAtIndex:j] objectForKey:@"x coord"];
    		YCoordinate1 = [[allEdinburghData objectAtIndex:j] objectForKey:@"y coord"];
    		
    		NSLog(@"Button %d's x coord as a string", j);
    		NSLog(XCoordinate1);
    		
    		xfloat = [XCoordinate1 floatValue];
    		yfloat = [YCoordinate1 floatValue];
    		
    		NSLog(@"Button %d's x coord as a float = %d", j, xfloat);
    		
    		xScaled = (320 * 
    				   (1 - 
    					((xfloat - 3.1417) / 0.1204)));
    		yScaled = (306 * 
    				   (1 - 
    					((yfloat - 55.9261) / 0.0665)));
    		
    		
    					 
    		[self createButton:xScaled AtYCoord:yScaled];
    		
    	}
    	
    	
    	[XCoordinate1 release];
    	[YCoordinate1 release];
    }

    and here's the Console Log:

    Code:
    Create All Events Buttons
     Button 0's x coord as a string
     55.9536
    Button 0's x coord as a float = -1610612736
    
    
     Button 1's x coord as a string
     55.9527
     Button 1's x coord as a float = 536870912
    why on earth is [string Floatvalue]; turning 55.9536 into -1610612736 ???!!

    Needless to say the dot-buttons don't appear on the screen!

    Could it be some weird memory issue? Or something silly I'm doing?...
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    It's not.
    Bingo! Think about what %d in your NSLog is supposed to do.
     
  3. thread starter macrumors newbie

    Joined:
    Apr 30, 2010
    #3
  4. macrumors 603

    Joined:
    Aug 9, 2009
    #4
    This code is dangerous. What happens if the string contains a '%'?

    Maybe you know for sure that can't happen here, but once you start using the technique, it can end up in places where Bad Things can happen. At best, you have a bug. At worst, you have an exploitable security flaw.
     

Share This Page