views:

38

answers:

3

Hello There!

I have a method that receives a number in a NSString format.

I wish to convert this string to a double which I can use to calculate a temperature.

Here's my method.

NSString *stringTemp = text; // text is a NSString 
NSLog(@"%@",stringTemp); // used for debugging
double tempDouble = [stringTemp doubleValue];
NSLog(@"%f",tempDouble); // used for debugging

Please note I put the NSLog commands here just to see if the number was correct. The latter NSLog returns a value of 82.000000 etc. (constantly changes as it's a temperature).


Next I wanted to use this double and convert it to a Celsius value. To do so, I did this:

double celsiusTemp = (5 / 9) * (tempDouble - 32);

Doing this: NSLog(@"%d", celsiusTemp); , or this: NSLog(@"%f", celsiusTemp); both give me a value of 0 in the console. Is there any reason why this would be happening? Have I made a stupid mistake somewhere?

Thank you for your help!

+2  A: 

Try doing (5.0 / 9.0). If you only use int to do math that expect a double from the answer will just be an int and in this case always 0

Rudiger
Thanks for the quick reply! I've give it a shot...
willingfamily
It worked! Thanks! Forgive me for asking, but what is the placeholder value to get the answer merely to the tenth's place?
willingfamily
Heh, beat the masses by about 1 min. Think its safe to say thats probably your issue
Rudiger
It only works when you output the value to the UILabel or NSLog as it will always be stored in memory the way amount of bits that the type is (int / double), think its something like @"%.1f"
Rudiger
Just tested it, it was actually `%.1f`, but thanks again for your quick help, my friend!
willingfamily
Yeah just realised you meant 1 decimal place not 2. Vote up!
Rudiger
A: 

5 / 9 is the division of two integers, and as such uses integer division, which performs the division normally and then truncates the result. So the result of 5 / 9 is always the integer 0.

John Calsbeek
Oh, so it doesn't round? It just takes the units place (which is 0). I see! Thanks for the info!
willingfamily
Right, it's exactly the same as if you cast the result to an int: (int)0.5555
John Calsbeek
Interesting! Well, now I know! :)
willingfamily
A: 

Try:

double celsiusTemp = (5.0 / 9) * (tempDouble - 32); 

If you evaulate (5/9) as an integer, then it is just 0.

BobbyShaftoe
Thank you for pointing that out!
willingfamily