Fix: Int Missing Leading Zeros When Converted to String in Swift

Fix: Int Missing Leading Zeros When Converted to String in Swift

Written by

in

Quick answer: Use String(format: “%02d”, myInt) with Foundation imported to pad integers with leading zeros. For locale-aware formatting, use NumberFormatter with minimumIntegerDigits set.

Why this happens

Swift’s default String interpolation (\(myInt)) prints integers without any padding. The standard library does not include a built-in padding method on Int or String; that capability lives in Foundation via NSString-style format strings or NumberFormatter. Without importing Foundation (or UIKit/AppKit, which re-export it), you cannot use the format specifiers that add leading zeros.

How to fix it

1. Use String(format:_:) — simplest for fixed-width padding

Import Foundation and use the %0Nd format specifier where N is the total field width.

import Foundation

for i in 1...3 {
    let padded = String(format: "%02d", i)
    print(padded) // 01, 02, 03
}
  • %02d → minimum 2 digits, pad with zeros.
  • %04d → minimum 4 digits (0001, 0010, 0100).
  • Values wider than the field print in full (e.g., 100 with %02d yields "100").

2. Use String(format:arguments:) — useful when arguments are in an array

import Foundation

let numbers = [1, 2, 10, 100]
let formatted = numbers.map { String(format: "%02d", arguments: [$0]) }
print(formatted) // ["01", "02", "10", "100"]

This initializer takes a [CVarArg] array, handy for dynamic argument lists.

3. Use NumberFormatter — locale-aware and configurable

import Foundation

let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
formatter.maximumIntegerDigits = 2 // optional: cap width
formatter.allowsFloats = false

for i in 1...3 {
    if let str = formatter.string(from: NSNumber(value: i)) {
        print(str) // 01, 02, 03
    }
}

Advantages:
– Respects user’s locale (e.g., Arabic-Indic digits).
– Can combine with groupingSeparator, positivePrefix, etc.
– Thread-safe when instantiated per use or cached on a serial queue.

4. Swift 5.9+ FormatStyle (Foundation) — modern, type-safe

import Foundation

let style = IntegerFormatStyle<Int>().precision(.integerLength(2))
for i in 1...3 {
    print(i.formatted(style)) // 01, 02, 03
}

IntegerFormatStyle is the direction Apple is moving; it works with FormattedString and SwiftUI Text.

How to prevent it

  • Always import Foundation (or UIKit/AppKit) in files that format numbers.
  • Define a small helper if you repeat the pattern:
    swift
    extension Int {
    func zeroPadded(to width: Int) -> String {
    String(format: "%0*d", width, self)
    }
    }
    // Usage: 7.zeroPadded(to: 3) // "007"
  • Prefer NumberFormatter or FormatStyle when the output must respect the user’s locale.

FAQ

Does String(format:) work on Linux and Windows?

Yes. Foundation on non-Apple platforms includes String(format:_:) and NumberFormatter, so the same code compiles cross-platform.

Can I pad with characters other than zeros?

Not with the %0Nd specifier. For custom pad characters, build the string manually: String(repeating: "X", count: max(0, width - "\(n)".count)) + "\(n)".

Is there a performance difference between the methods?

String(format:) is fastest for one-off calls. NumberFormatter has higher setup cost but is negligible when reused. FormatStyle is optimized for repeated use in SwiftUI pipelines.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.