I want to display the specified value as a character string according to the specified format. In short, I want to do something like the following in C language.
sprintf.c
sprintf(str, "%.2f", pi)
There is a String type initializer that takes a format string as an argument, so use that.
stringformat.swift
let pi = 3.14159
let str = String(format: "%.2f", pi)
print(str)
Output result
3.14
It can also be used when rounding off and displaying in integer notation.
stringformat2.swift
let height = 182.9
let str = String(format: "%.0f", height)
print(str)
Output result
183
You can also take a String type as an argument.
In this case, use % @
as the format string.
stringformat3.swift
let s1 = "Hot"
let s2 = "Natsu"
let str = String(format: "%@Is%@I don't know.", , )
Output result
It's hot.
Xcode: 11.7 iOS: 13.7 Swift version: Swift5
that's all
Recommended Posts