views:

65

answers:

3

This is really weird, hopefully a fresh pair of eyes can help me figure this out. I happen to be using this code in an iPhone App, but I believe it's using simple C code so not sure this makes a difference or not. I have the user input a number (in this case the num will be 2.2). I then divide that number by 0.2.

On my calculator I get the answer of 11.

However, using the following code I get the answer of 10:

NSString *userNameFour = txtUserName4.text; 
double numFour = [userNameFour intValue];

double t_psd = numFour/0.2;

so now when I print the variable t_psd, I get 10.000000. What am I doing wrong here?

+4  A: 

That intValue bit looks suspicious... my guess is that numFour ends up being 2.0 rather than 2.2. Are you sure you didn't mean doubleValue?

Try this:

NSString *userNameFour = txtUserName4.text; 
double numFour = [userNameFour doubleValue];

double t_psd = numFour / 0.2;

(This is one issue I have with numeric parsers which just stop when they reach a character they don't expect. If you'd been using Java or .NET with Integer.parseInt or int.Parse the error would have been obvious - an exception would have been thrown saying that "2.2" isn't a text representation of an integer.)

Jon Skeet
+3  A: 

[userNameFour intValue] gives back (int) 2, which casts into (double) 2.0 when you assign it to numFour. And 2.0 / 0.2 = 10.0.

You want to use [userNameFour doubleValue].

ephemient
+2  A: 

intValue converts your string to an int, not a double. You want doubleValue instead :)

Kornel Kisielewicz
ah! You all that have answered are brilliant! I really appreciate your help :)
HollerTrain
i wish i could mark all of these the right answer.
HollerTrain
Funny, it turned out that the shorter the answer is the better O.o
Kornel Kisielewicz