by Sai gowtham

Convert int to string with leading zeros in Swift

To convert int to a string by adding leading zeros, we can use the Strings init(format:_:) initializer.

Here is an example, that adds leading 0 to the 1.

import Foundation

let str1 = String(format: "%02d", 1);

print(str1);

Output:

01

If you want to add two leading zeros, you can do it like this.

import Foundation

let string0 = String(format: "%03d", 1);
print(string0); // 001

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course