Take the 2-minute tour ×

How can i build a NSString variable consisting of string and float variables?

I assume i need to cast the floats to strings, but i cant see how this is done without creating alot of messy and ugly code.

I want to build something like this: String+ Float+ String+ Float

Thanks in advance.

share|improve this question
Strings are very different in Objective C from their Java counterparts. See my answer for an explanation. –  iamataptool Apr 29 '12 at 20:33
add comment

4 Answers

up vote 3 down vote accepted

That is not how Objective C works. In Java, you would use:

String yourString = string1 + " " + float1 + " " + string2 + " " + float2;

You cannot do the same in Objective C. To do something to the same effect, you would need:

NSString* yourString = [NSString stringWithFormat:@"%@ %f %@ %f", string1, float1, string2, float2];

This would result in the equivalent to the Java statement. %@ indicates you want to format an object into the string, and %f indicates a floating point value.

When formatting floats in an NSString, you can specify how many decimal places you want to truncate to by placing a value in between the % and f. For example, to round the first float to 2 decimal places and the second one to 5 decimal places:

NSString* yourString = [NSString stringWithFormat:@"%@ %.2f %@ %.5f", string1, float1, string2, float2];
share|improve this answer
add comment


NSString *str = [NSString stringWithFormat:@"Some text %f some more text %f", floatVar, anotherFloat];
share|improve this answer
@Java Updated answer –  Teak Apr 29 '12 at 20:31
add comment

To answer the question as asked:


NSString *str1 = @"string one";
NSString *str2 = @"string two";

float f1 = 1.0;
float f2 = 2.0;

NSString *answer = [NSString stringWithFormat:@"%@: %f. %@: %f.", str1, f1, str2, f2];
NSLog(@"%@", answer); // This will print "string one: 1.000000. string two: 2.000000."
share|improve this answer
add comment
float sampleFloatVariable = 50.0;

NSString *floatintoText = [NSString stringwithFormat:@"%f",sampleFloatVariable];

NSLog(@" float text %@",floatintoText);
share|improve this answer
thanks alot. But please check my updated explaination. –  JavaCake Apr 29 '12 at 20:31
string + float ..didnt understood it.. can you give an example ..what you want to achieve –  Shubhank Apr 29 '12 at 20:32
add comment

Your Answer


