DEV Community

Uzochukwu Eddie Odozi
Uzochukwu Eddie Odozi

Posted on • Edited on

Number Formatter in Javascript

In this short tutorial, we are going to create a simple number formatter using Javascript. Numbers greater than or equal to a thousand will be shortened and replaced with number category symbol. Examples of symbols:

Thousand    = K
Million     = M
Billion     = G
Trillion    = T
Quadrillion = P
Quatrillion = E

And so on.

The method below is the number formatter functionality

numberFormatter(number, digits){
    const symbolArray = [
      { value: 1, symbol: "" },
      { value: 1E3, symbol: "K" },
      { value: 1E6, symbol: "M" },
      { value: 1E9, symbol: "G" },
    ];
    const regex = /\.0+$|(\.[0-9]*[1-9])0+$/;
    let result = "";

    for(let i = 0; i < symbolArray.length; i++) {
        if (number >= symbolArray[i].value) {
            result = (number / symbolArray[i].value).toFixed(digits).replace(regex, "$1") + symbolArray[i].symbol;
        }
    }
    return result;
}

Other values than can be added are

1E12 = 1000000000000
1E15 = 1000000000000000
1E18 = 1000000000000000000

Examples

numberFormatter(1000, 1) = "1K"
numberFormatter(10000, 1) = "10K"
numberFormatter(2134564, 1) = "2.1M"
numberFormatter(5912364758694, 3) = "5.912T"

You can follow me Twitter and also subscribe to my YouTube channel.

Top comments (0)