Leading zeros for Int in Swift
I'd like to convert an Int
in Swift to a String
with leading zeros. For example consider this code:
for myInt in 1 ... 3 {
print("\(myInt)")
}
Currently the result of it is:
1
2
3
But I want it to be:
01
02
03
Is there a clean way of doing this within the Swift standard libraries?
Assuming you want a field length of 2 with leading zeros you'd do this:
import Foundation
for myInt in 1 ... 3 {
print(String(format: "%02d", myInt))
}
output:
01 02 03
This requires import Foundation
so technically it is not a part of the Swift language but a capability provided by the Foundation
framework. Note that both import UIKit
and import Cocoa
include Foundation
so it isn't necessary to import it again if you've already imported Cocoa
or UIKit
.
The format string can specify the format of multiple items. For instance, if you are trying to format 3
hours, 15
minutes and 7
seconds into 03:15:07
you could do it like this:
let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
output:
03:15:07
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
#1. Using String
's init(format:_:)
initializer
Foundation
provides Swift String
a init(format:_:)
initializer. init(format:_:)
has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:_:)
:
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
#2. Using String
's init(format:arguments:)
initializer
Foundation
provides Swift String
a init(format:arguments:)
initializer. init(format:arguments:)
has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:arguments:)
:
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
#3. Using NumberFormatter
Foundation provides NumberFormatter
. Apple states about it:
Instances of
NSNumberFormatter
format the textual representation of cells that containNSNumber
objects and convert textual representations of numeric values intoNSNumber
objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter
that returns String?
from a Int
with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
For left padding add a string extension like this:
Swift 5.0 +
extension String {
func PadLeft( totalWidth: Int,byString:String) -> String {
let toPad = totalWidth - self.count
if toPad < 1 {
return self
}
return "".padding(toLength: toPad, withPad: byString, startingAt: 0) + self
}
}
Swift 3.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count
if toPad < 1 { return self }
return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
}
}
Using this method:
for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}
Swift 3.0+
Left padding String
extension similar to padding(toLength:withPad:startingAt:)
in Foundation
extension String {
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.characters.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.characters.count)
return padding + self
}
}
Usage:
let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"