Ali
Ali

Reputation: 2025

Percentage with NSString

I have an input NSString and I want to get ouput with % at the end

I tried to do the following but it failed

NSLog([NSString stringWithFormat:@"%@%%", self.tName.text ] ); 

where tName is UITextfield

the problem is at console if i typed A the output will be A not A%

Any suggestion to solve that?

Upvotes: 0

Views: 1137

Answers (3)

Itai Ferber
Itai Ferber

Reputation: 29834

You're not using NSLog() correctly. NSLog() is meant to be called with a constant format string (%@%%, for instance), and be passed in arguments. What you're doing is parsing these arguments beforehand, and then passing the string you want to print to NSLog(), which doesn't work.

When you write [NSString stringWithFormat:@"%@%%", @"Hello!"], the string you get back is @"Hello!%", which is what you want to print. However, when you pass it into NSLog(), it thinks that that is the format string it needs to parse, sees the single percent sign and doesn't know what to do (it expects getting something after the percent sign), so it ignores it. Essentially, what you're doing is this:

NSLog(@"Hello!%");

Try it out and you'll see it won't work. Using a correct NSLog() call will fix your problem:

NSLog(@"%@%%", self.tName.text);

Read up on NSLog() and its variable counterpart, NSLogv() here.

Upvotes: 3

Ahmad Kayyali
Ahmad Kayyali

Reputation: 8243

I just have tested your case like the following:

NSString *s = @"100";
NSLog(@"%@%%",s);

the Output was: 100%

try this would it make a difference?

 NSLog(@"%@%%",self.tName.text);

Upvotes: 0

John Parker
John Parker

Reputation: 54445

I'm not sure what your problem is, but simply using %% will output the percentage sign, as per the String Format Specifiers section of the String Programming Guide.

Upvotes: 0

Related Questions