why is floatValue method turning strings into nonsense?

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

  1. macrumors newbie

    Apr 30, 2010
    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:

    -(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);
    		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:

    Create All Events Buttons
     Button 0's x coord as a string
    Button 0's x coord as a float = -1610612736
     Button 1's x coord as a string
     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


    Staff Member

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

    Apr 30, 2010
  4. macrumors 604

    Aug 9, 2009
    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