PDA

View Full Version : why is floatValue method turning strings into nonsense?




LoopLoop
Jul 19, 2010, 02:09 PM
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);
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:

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?...



dejo
Jul 19, 2010, 02:15 PM
why on earth is [string Floatvalue]; turning 55.9536 into -1610612736 ???!!
It's not.
Or something silly I'm doing?...
Bingo! Think about what %d in your NSLog is supposed to do.

LoopLoop
Jul 19, 2010, 02:23 PM
Ah ha, cheers dejo - %f is the answer!

http://www.cocoadev.com/index.pl?NSLog

for anyone with similar holes in knowledge.

thanks

chown33
Jul 19, 2010, 03:00 PM
NSLog(XCoordinate1);



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.