Check group of millions using javascript

198 views Asked by At

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?

5

There are 5 answers

3
Skwal On BEST ANSWER

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);
});
0
Andy On
$.each(myObj, function(index, value) {
  var check = parseInt(value / 1000000, 10);
  if (check > 0) {
    $("#account" + index).html(check + 'M+');
  } else {
    $("#account" + index).html(value);
  }
});

Will produce: 5M, 156726, 889338.

Fiddle

0
Dakotah Hicock On

You can try:

if(value = 1000000)
    $("#account" + index).html("1M");
if(value > 1000000 && value < 2000000) {
    $("#account" + index).html("1M+");
}

This looks cleaner. Another option is to declare constants so oneM = 1000000, twoM = 2000000 then you just reference those variables

0
halkujabra On
var x = 1000000;
    for(i = 1; i < 10 ; i++)
    {
    if(value > i*x && value < (i+1)*x)
    $("#account" + index).html(i+"M+");
    }

Follow the same pattern if you wanna take it to billions

0
RobH On

How about starting your comparisons from high to low, starting with the largest value that you'll be expecting, like so:

if (value > 3000000)
    $("#account" + index).html("3M+");
else if (Value > 2000000)
    $("#account" + index).html("2M+");
else if (Value > 1000000)
    $("#account" + index).html("1M+");
else if (Value = 1000000)
    $("#account" + index).html("1M");