0

I know how to format a float when displaying it as part of an NSString (see e.g. Make a float only show two decimal places) but is there a way to dynamically set the number of decimal digits to be displayed? For example, if I know I want int dig digits can I modify the following expression to format my float as desired?

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

I know I can do this with NSNumberFormatter, but I'm looking for a more direct method.

Community
  • 1
  • 1
sunny
  • 3,853
  • 5
  • 32
  • 62

1 Answers1

0

See the IEEE printf specification for everything you need to know about format specifiers.

You want:

int dig = 4; // for example
NSString *formattedNumber = [NSString stringWithFormat:@"%.*f", dig, myFloat];

dig is used where the * is to indicate the number of digits after the decimal point.

rmaddy
  • 314,917
  • 42
  • 532
  • 579