Alexandra
Alexandra

Reputation: 11

Convert long number in to 1M, 1K etc in Javascript

How can I stop loop when the first time if condition is true?

<p id="numb"></p>

And here is my code javascript, Where i did mistake? i want that when the condition is true the loop stops and don't check other variants?

function round (number) {
    var str = number.replace(/[, .]/g, "");
    var numb = parseInt(str);
    var point = {
        "T": Math.pow(10, 12),
        "B": Math.pow(10, 9),
        "M": Math.pow(10, 6),
        "K": Math.pow(10, 3)
    };

    Object.keys(point).forEach(function (key) {
        var pNumb = point[key];
       // console.log(pNumb);
      //  console.log(key);
        if (pNumb < numb) {
            var letter  = key;
            console.log(letter);
            var z = numb / pNumb;
            if (numb % pNumb !== 0) {
                document.getElementById("numb").innerHTML = z.toFixed(1) + letter;
            } else {
                document.getElementById("numb").innerHTML = z + letter;
            }
            return false;
        }

    });
}
    round("665,421,000")

Upvotes: 0

Views: 172

Answers (2)

Mark Reed
Mark Reed

Reputation: 95242

Returning false will not stop a forEach loop early. The only way to stop such a loop early is to throw an exception (which you need to catch outside the loop).

I normally recommend using a for...of loop instead of forEach, if you are using a new enough version of Javascript. But in this case, since you're calling forEach on the result of calling Object.keys() on the object (instead of the object itself), you can just use a for...in loop, which has been in Javascript forever.

Upvotes: 1

Francisco
Francisco

Reputation: 11476

Besides forEach not returning a value if you return from it, your code is wrong, because you're assuming object keys maintain their order, you should write something like this instead:

function round (number) {
    const str = number.replace(/[, .]/g, "");
    const numb = parseInt(str);
    const point = [
        ["T", Math.pow(10, 12)],
        ["G", Math.pow(10, 9)],
        ["M", Math.pow(10, 6)],
        ["K", Math.pow(10, 3)]
    ];

    for (const [key, pNumb] of point) {
        if (pNumb < numb) {
            const letter  = key;
            const z = numb / pNumb;
            if (numb % pNumb !== 0) {
                return z.toFixed(1) + letter;
            } else {
                return z + letter;
            }
        }
    }
}

You also have a typo, instead of "G", you have "B".

Upvotes: 0

Related Questions