How to correctly format strings to populate labels in Swift

Viewed 66

I have an app which have a segue paying data to an UIView and I need to display the percent sign after the number and also only one or two decimal digits. I’m doing as you can see below because I could not do the same from the first example below using “format:” into the second example.

    var dailyUviString: String {
        return String(format: "%.1f", dailyUvi!)
    }
    var dailyPopString: String {
        return String("\(dailyPop!*100) %")
    }

Any ideas ?

Thanks

1 Answers

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%"
Related