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?
zero should never be used as an extension on a primitive such as Int or Double . Instead, use the raw 0 value.
Just convert the string to an int and then back to a string again. It will remove the leading zeros. let numberString = "00123456" let numberAsInt = Int(numberString) let backToString = "\(numberAsInt!)" In this case the string is defined so it will never be nil.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With