Avatar ·

How to add leading zeros to an Int number in Swift for display?

Hi everyone! I'm new to Swift and ran into a problem that seems simple, but I can't find the right solution.\n\nI need to display a number (Int) with leading zeros. For example, I have the number 7, and I want to display it as "007" (three digits). Or the number 42 should become "042". If the number is greater than 99, then zeros are not needed — for example, 123 should remain "123".\n\nI tried doing this:\n\n```swift\nlet number = 7\nlet formatted = "0" + String(number) // Results in "07", but I need "007"\n```\n\nBut this only works for one zero. If I write:\n\n```swift\nlet number = 7\nlet formatted = "00" + String(number) // "007" — works for 7, but for 42 it will be "0042", but I need "042"\n```\n\nSo I can't just add a fixed number of zeros, because the number can be of different lengths.