Getting 'nan' when inserting method in stringWithFormat
I have simplifed some methods for ease of understanding and correction of the error. I get a 'nan' instead of getting the number and don't understand why. I want to put the getNumber method inside the return开发者_StackOverflow社区 statement. When I have the method inside it returns a string of nan but when I just put the 26 inside it returns 26, what I want.
-(double) getNumber { return 26; }
-(NSString *) convertToString {
return [NSMutableString stringWithFormat: @"%Lf",[self getNumber]];
// returns 'nan' when I replace [self getNumber] with 15 I get 15
}
You have a couple problems in your code.
- Return a double, not an integer in
getNumber
. While automatic coercion will occur, write clean code. - Use the
%g
format specifier, not%Lf
.%g
is for doubles.
You might want to use "%f" instead of "%Lf", since you are passing a double
, not a long double
It's your format specifier. You should use "%g" to format a double.
精彩评论