0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please point me to documentation of usage of * in NSString format?
@DeepakSharma: developer.apple.com/reference/foundation/nsstring/… links to developer.apple.com/library/content/documentation/… which in turn links to pubs.opengroup.org/onlinepubs/009695399/functions/printf.html. On that page: "A field width, or precision, or both, may be indicated by an asterisk ..."
Thanks @MartinR. I was getting there, but I had 3 pets demanding to be fed immediately.
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.