how to correctly format strings to populate labels in swift?

If you would like to include the percentage sign in your format you just need to add it twice:

var dailyPopString: String {
    String(format: "%.1f%%", dailyPop!*100)   // "50.0%"
}

Another option is to use NumberFormatter. Note that when using NumberFormatter with numberStyle set to .percent you don’t need to multiply your value by 100:

let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 1
numberFormatter.numberStyle = .percent
numberFormatter.string(for: dailyPop!)  // "50.0%"

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top