How to Convert Number to String with Leading Zeros in TypeScript?

Have you ever needed to display ZIP codes, invoice numbers, or employee IDs in your TypeScript application, only to find your numbers missing those all-important leading zeros? In TypeScript, you can add leading zeros to numbers.

In this tutorial, I’ll walk you through multiple methods for converting numbers to strings with leading zeros in TypeScript.

First, let me explain why we need to add leading zeros. Below are some examples. This will help you understand.

  • ZIP codes: 02139 (Cambridge, MA)
  • Social Security Numbers: 007-45-6789
  • Employee IDs: 00012345
  • Bank account numbers: 0000456789

If you store these as numbers, JavaScript and TypeScript will drop the zeros by default. That’s why formatting is essential for accurate display.

Method 1: Using padStart() for Simple Formatting

My go-to method for most cases is padStart(). This string method is perfect for ensuring a string has a specified length, padding it with zeros if needed.

Let me show you an example of using the padStart() method to add leading Zeros to a string in TypeScript.

Example: Format a ZIP Code

Here is an example that demonstrates how to add leading zeros to a zip code using the TypeScript code below.

const zipCode = 2139; // Massachusetts ZIP code (should be '02139')
const zipString = zipCode.toString().padStart(5, '0');
console.log(zipString); // Output: '02139'

How it works:

  • Convert the number to a string.
  • Use padStart(totalLength, '0') to add the necessary zeros.

Here is the exact output in the screenshot below:

Convert Number to String with Leading Zeros in TypeScript

This is especially handy when working with US ZIP codes, which are always 5 digits.

Check out Typescript Split String

Method 2: Template Literals for Quick Zero Padding

For fixed-width numbers, template literals offer a concise alternative. This is useful if you always want, say, a 9-digit Social Security number.

Example: Social Security Number

Here is an example.

const ssn = 7456789; // Should be '007456789'
const ssnString = `${ssn}`.padStart(9, '0');
console.log(ssnString); // Output: '007456789'

The logic is the same as with ZIP codes—just adjust the total length.

You can see the exact output in the screenshot below:

typescript convert number to string with leading zero

Check out Convert Typescript Dictionary to String

Method 3: Custom Function for Flexible Leading Zeros

If you need to reuse this logic across your application, or if the length varies, a helper function is a great choice.

function addLeadingZeros(num: number, length: number): string {
  return num.toString().padStart(length, '0');
}

// Example: Employee ID
const employeeId = 12345;
const formattedId = addLeadingZeros(employeeId, 8);
console.log(formattedId); // Output: '00012345'

This approach keeps your code DRY and makes it easy to format any number with any length.

Read How to Initialize an Empty Dictionary in TypeScript

Method 4: Using Intl.NumberFormat for Advanced Formatting

For more advanced formatting—especially if you need to localize the output—Intl.NumberFormat can help, though it’s typically used for currency and number formatting. With a little tweaking, you can use it for leading zeros too.

Here is an example.

const bankAccount = 456789;
const formatter = new Intl.NumberFormat('en-US', {
  minimumIntegerDigits: 10,
  useGrouping: false,
});
const formattedAccount = formatter.format(bankAccount);
console.log(formattedAccount); // Output: '0000456789'

This method is powerful if you’re already using Intl.NumberFormat elsewhere in your app.

Method 5: String Concatenation

Before padStart, developers often used string concatenation. While not as clean, it still works.

Here is an example of using string concatenation to add leading zeros to a string in TypeScript.

const invoiceNum = 987;
const paddedInvoice = ('00000000' + invoiceNum).slice(-8);
console.log(paddedInvoice); // Output: '00000987'

This method is less recommended today, but it’s good to know for legacy codebases.

Read How to Check the Type of an Object in TypeScript

    Convert Number to String with Leading Zeros in TypeScript Examples

    Now, let me give some examples of converting a number to a string with leading zeros in TypeScript.

    1. Display ZIP Codes in an Address Form

    Here is an example of displaying ZIP codes in an address form.

    function formatZipCode(zip: number): string {
      return zip.toString().padStart(5, '0');
    }
    
    // Usage
    const userZip = 902; // Beverly Hills
    console.log(formatZipCode(userZip)); // Output: '00902'

    You can see the exact output in the screenshot below:

    Convert Number to String with Leading Zeros in TypeScript Examples

    2. Generate Employee Badges

    Here is how to generate an employee badge by adding leading zeros to a string.

    function formatEmployeeId(id: number): string {
      return addLeadingZeros(id, 7);
    }
    
    const badgeId = 56;
    console.log(formatEmployeeId(badgeId)); // Output: '0000056'

    3. Format Bank Account Numbers for Statements

    Here is an example of how to generate a formatted bank account number for statements by adding leading zeros to a string.

    function formatAccountNumber(account: number): string {
      return addLeadingZeros(account, 10);
    }
    
    const accountNum = 789654;
    console.log(formatAccountNumber(accountNum)); // Output: '0000789654'

    Summary

    In this tutorial, I explained how to add leading zeros to numbers in TypeScript using different methods, such as using padStart(), template literals, or a custom function. This way, you can always ensure your numbers are formatted correctly for display.

    • For most cases: Use padStart() for simplicity and readability.
    • For reusable logic: Create a helper function.
    • For localization or advanced formatting: Consider Intl.NumberFormat.
    • For older codebases: You may encounter string concatenation.

    Try out these methods in your own projects. If you have any questions or would like to share your approach, please drop a comment below—I’d love to hear how you’re using these methods!

    You may also like the following tutorials:

    Power Apps functions free pdf

    30 Power Apps Functions

    This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

    Download User registration canvas app

    DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

    Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App