Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (13.1k points)

Can anyone help me how I can able to convert an integer to a abbreviation in JavaScript. I want to achieve something like this:

0                      "0"

12                    "12"

123                  "123"

1234                "1.2k"

12345                "12k"

123456              "0.1m"

1234567             "1.2m"

12345678             "12m"

123456789           "0.1b"

1234567899          "1.2b"

12345678999          "12b"

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the below code, which will fulfill your requirements:

function abbreviateNumber(value) {

    var newValue = value;

    if (value >= 1000) {

        var suffixes = ["", "k", "m", "b","t"];

        var suffixNum = Math.floor( (""+value).length/3 );

        var shortValue = '';

        for (var precision = 2; precision >= 1; precision--) {

            shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));

            var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');

            if (dotLessShortValue.length <= 2) { break; }

        }

        if (shortValue % 1 != 0)  shortValue = shortValue.toFixed(1);

        newValue = shortValue+suffixes[suffixNum];

    }

    return newValue;

}

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Tutorial for Beginners | Java Programming:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 14, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...