Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 523
Jeehut Avatar asked Aug 29 '14 10:08

Jeehut


People also ask

Is 0 an int in Swift?

zero should never be used as an extension on a primitive such as Int or Double . Instead, use the raw 0 value.

How do I remove leading zeros in Swift?

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.


1 Answers

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 
like image 179
vacawama Avatar answered Oct 18 '22 19:10

vacawama