Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check group of millions using javascript

Tags:

javascript

Here I'm returning an array with values in which is formatted as such

var myObj = {
    "account": "5622555",
    "account1": "156726",
    "account3": "889338",
    etc....
}

I'm then formatting this array and assigning the values to a HTML div, here's the code I'm using.

$.each(myObj, function(index, value){
    $("#account" + index).html(value);
});

How can I change the value to display in groups of millions etc.. like so

if(value > 1000000) {
    if(value < 2000000) {
        if(value != 1000000) {
            $("#account" + index).html("1M+");
        } else {
            $("#account" + index).html("1M");
        }
    }
}
if(value > 2000000) {
    if(value < 3000000) {
        if(value != 2000000) {
            $("#account" + index).html("2M+");
        } else {
            $("#account" + index).html("2M");
        }
    }
}
if(value > 3000000) {
    if(value < 4000000) {
        if(value != 3000000) {
            $("#account" + index).html("3M+");
        } else {
            $("#account" + index).html("3M");
        }
    }
}

What's a quicker way of performing such if statements so I don't have to write the complete number?

like image 385
Curtis Avatar asked Nov 30 '25 02:11

Curtis


1 Answers

The easiest way would be

$.each(myObj, function(index, value){
    if(value > 999999) 
        $("#account" + index).html(String.prototype.replace.call(value, /(\d)(\d{6})/, "$1" + (value%1000000 > 0 ? 'M+' : 'M'), 'g'));
    else
        $("#account" + index).html(value);
});
like image 94
Skwal Avatar answered Dec 02 '25 17:12

Skwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!