DEV Community

Michael Willian Santos
Michael Willian Santos

Posted on

JavaScript - Abbreviate Numbers

Case

I am working into a website in which I handle with a lot of data and by this, the end user (client) shall see the results and values. So, I was caught into a problem... The overall display of the values.
While in some cases for the user, it will be interesting to see the raw value (like, 13.640.333.000)... in another, just the abbreviation of the value will be acceptable (13.64 B).
So I went to look forward a way to solve this problem of mine — looking around the community. But, the scripts that I have found either is "heavy" for this purpose or it is very fancy for this.
Then... I end up creating my own, tiny solution...

Warning

As I'm pretty busy with my works recently, I'll not be able to share my codes with the community (I'll share some 'react hooks' and snippets that I use often).
However, since I feel that this can be very useful... I'll share here xD

Code

/**
 * Abrreviete the number by unit
 * @param {Number|String} number
 * @param {Object} config
 * @param {Boolean} config.absolute if it will replace the 'x.yyy', '.yyy', for
 * empty space. Like, '13.4' to '13'
 * @param {Number} config.factor the factor on 'toFixed'
 * @param {Array} config.unit
 * @param {Boolean} config.numeric if the final value will be the type 'number'
 * or 'string'
 */

function abbreviate (number, config = {}) {
    if (typeof config !== 'object') config = {}
    if (!config.hasOwnProperty('factor')) config.factor = 2
    if (!config.hasOwnProperty('absolute')) config.absolute = true
    if (!config.hasOwnProperty('unit'))
        config.unit = ['', 'K', 'M', 'B', 'T', 'Q']
    if (!config.hasOwnProperty('numeric')) config.numeric = false
    let value = String(number).replace(/(\.|\)|\(|\,)/g, '')
    let length = value.length - 1
    const unit_index = ~~(length / 3)
    value = eval(
        `parseFloat(${value} / 1e${unit_index * 3}).toFixed(${config.factor})`
    )
    //console.log(config)

    if (!!config.absolute) value = value.replace(/\.(\d+)$/, '')
    return !!config.numeric ? +value : `${value} ${config.unit[unit_index]}`
}

How to Use

Copy the code on the DevTools of your Browser and let's test it xD

Default

You can use the standard way...
Like:

abbreviate("123458886")
// "123 M"

or to control decimal places

abbreviate("123458886", {absolute: false, factor: 3})
// "123.459 M"

Bye

Well, that is it... If it helps you or if you have some feedback/suggestion, let me know :)... Any doubt, please, comment as well

Top comments (0)