I'm using XCODE with Swiftui. I want to know how I can format percentages in the program to whole numbers with a % sign without any decimal places to the screen. For instance if the program figures 33.3333 I want to print 33% to the screen. If I have 67.85762 in the program I want to print 67% (or 68% if it can be rounded) to the screen. Please help. Thanks
format percentages
print(String(format: "%.0f%%", 33.3333))
prints 33%
Explanation:
String(format: "%.2f", value)
%.2f
formats and rounds to the number of decimal places given, in this case, 2.
For zero decimal places you just use 0
, i.e.:
String(format: "%.0f", value)
To display the percentage sign as a percentage sign, and not be interpreted by the formatting you need to add in two of them: String(format: "%.2f%%", value)
So: String(format: "%.2f%%", 67.85762)
is 67.86%
.
String(format:...)
rounds accordingly, i.e.:
let pi = 3.1415926535
String (format: "%.10f", pi) // "3.1415926535"
String (format: "%.9f", pi) // "3.141592654"
String (format: "%.8f", pi) // "3.14159265"
String (format: "%.7f", pi) // "3.1415927"
String (format: "%.6f", pi) // "3.141593"
String (format: "%.5f", pi) // "3.14159"
String (format: "%.4f", pi) // "3.1416"
String (format: "%.3f", pi) // "3.142"
String (format: "%.2f", pi) // "3.14"
String (format: "%.1f", pi) // "3.1"
String (format: "%.0f", pi) // "3"
Thank you.
I get 0%. Here's my code:
print(tipc)
let percentString = String(format: "%.0f%%", tipc)
print(percentString)
18.181818181818183
0%.
What did I do wrong?