I need to pass some float value to the NSString string. Which Deputy should I use instead of %f in order for the code (below) to work correctly?

 #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { float x = 323.13; NSString *text1 = [NSString stringWithFormat: @"Переменная x = " @"%.f" , "x"]; NSLog(text1); } return 0; } 

Output : переменная x = 0

It is necessary that there be a переменная x = 323.13 What is needed to fix this?

    2 answers 2

    if it is known that there will be two decimal places then like this:

     float x = 323.13; NSString *text1 = [NSString stringWithFormat: @"Переменная x = %.2f" , x]; NSLog(text1); 
    • Thank. And then I killed three hours in search. - Andrew Kachalin

    Max Mikheyenko’s answer is correct and sufficient for this case, however, it’s not very suitable for displaying a similar number in the interface in production.
    In a real application, it is better to use the NSNumberFormatter class, which can be easily configured, and also takes into account the current locale when converting a number to a string and back (for example, the Russian locale uses a comma rather than a period as a divider of the fractional part).

    Then the specified example will turn into the following:

     float x = 323.13; NSNumberFormatter* formatter = <Создаём и настраиваем форматтер> NSString *text1 = [NSString stringWithFormat: @"Переменная x = %@" , [formatter stringFromNumber:@(x)]]; NSLog(text1); 

    And the output to the log will be based on the selected locale (system or installed in the formatter).