NSString stringWithFormat syntax

671 Views Asked by At

In one of the sample codes by Apple, I see the following lines:

int digits = MAX( 0, 2 + floor( log10( newDurationSeconds)));
self.exposureDurationValueLabel.text = [NSString stringWithFormat:@"1/%.*f", digits, 1/newDurationSeconds];

I am not able to understand the syntax, there are two arguments to stringWithFormat: but only one % sign. I understand it is string value of 1/newDurationSeconds upto N=digits but the syntax is something I don't get.

And how do I translate it to Swift 3?

2

There are 2 best solutions below

3
vacawama On BEST ANSWER

The first parameter supplies the number of decimal digits desired and is represented by the *, and the second value is the number.

In Swift:

String(format: "1/%.*f", digits, 1/newDurationSeconds)

Note: This capability is supplied by the Foundation framework. You must import Foundation (or import UIKit or import Cocoa) for it to work.

You can find documentation for the format string here (Apple's Documentation) and here (IEEE printf specification).

In the second document, the * is explained:

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.

0
Josh Homann On

You can use NumberFormatter instead of C style format strings; its often clearer, though longer:

  let newDurationSeconds = Double(10.7)
  let digits = max(0,2 + (log10(newDurationSeconds).rounded(.towardZero)))
  let formatter = NumberFormatter()
  formatter.maximumFractionDigits = Int(digits)
  let s = formatter.string(from: NSNumber(value: newDurationSeconds))