How to display percentage values in SwiftUI

iOSdev / SwiftUI

How to display percentage values in SwiftUI

Lately, one user of my mood tracking app Emo requested that I add percentage values to my Statistics screen. Since displaying percentage values is a little harder than displaying numbers, I thought I would share a few ways of doing this in this article.

Let's say we have two Doubles and a total value equal to the sum of them.

let value1: Double = 1
let value2: Double = 2
let total = value1 + value2 // 3

Option 1

Now, if we want to check what percentage of the total is value1 and display this percentage in SwiftUI with 0 fraction digits, we could do something like this:

Text("\(String(format: "%.0f", (value1 / total * 100)))%")

Option 2

Since iOS 15, there is another way, though, and you may find it more readable:

Text((value1 / total).formatted(
    .percent.precision(.fractionLength(0)))
)

Both options will result in the same text:
33% (for value1)
67% (for value2)

As you can probably guess, to change the precision to display 2 fraction digits in your percentages, you can modify both versions of the code as follows:

Text("\(String(format: "%.2f", (value1 / total * 100)))%") // %.2f

Text((value1 / total).formatted(
    .percent.precision(.fractionLength(2))) // fractionLength(2)
)

When you display fraction digits, you will notice another difference between both methods. The first one will always display percentage values the same way, as it's a hard-coded format (for example, 33.33%).

The second one, using the formatted() method, takes the user's locale into consideration. So the percentage value may be displayed as 33.33% or 33,33%, depending on the locale. The same applies to other locale-specific rules, like grouping separators (e.g., "10,000" in one country and "10 000" in another).

This means that the second option is not only more readable but also a better choice if the app is localized, as with the formatted() method, all the values will be properly formatted based on the user's locale.

UPDATE: Option 3

After I published this article, Łukasz Rutkowski reminded me on Mastodon about another similar method (which also formats numbers properly based on locale):

Text((value1 / total),
    format: .percent.precision(.fractionLength(0))
)

If you know another way to display percentages in SwiftUI, feel free to share it in the comments.

Thank you for reading!

If you want to support my work, please like, comment, share the article and most importantly...

📱Check out my apps on the App Store:
https://apps.apple.com/developer/next-planet/id1495155532

Credits

Thank you to Arnaud Joubay and Avery Vine for your input on app localization, and to Łukasz Rutkowski for suggesting Option 3.