Skip to content Skip to sidebar Skip to footer

Javascript Convert Numbers To Different Formats Or String Alternative

UPDATED: Using javascript or jQuery, how can I convert a number into it's different variations: eg: 1000000 to... 1,000,000 or 1000K OR 1000 to... 1,000 or 1K OR 1934 and 1234 to

Solution 1:

You can add methods to Number.prototype, so for example:

Number.prototype.addCommas = function () {
    var intPart = Math.round(this).toString();
    var decimalPart = (this - Math.round(this)).toString();
    // Remove the "0." if it existsif (decimalPart.length > 2) {
        decimalPart = decimalPart.substring(2);
    } else {
        // Otherwise remove it altogether
        decimalPart = '';
    }
    // Work through the digits three at a timevar i = intPart.length - 3;
    while (i > 0) {
        intPart = intPart.substring(0, i) + ',' + intPart.substring(i);
        i = i - 3;
    }
    return intPart + decimalPart;
};

Now you can call this as var num = 1000; num.addCommas() and it will return "1,000". That's just an example, but you'll find that all the functions create will involve converting the numbers to strings early in the process then processing and returning the strings. (The separating integer and decimal part will probably be particularly useful so you might want to refactor that out into its own method.) Hopefully this is enough to get you started.

Edit: Here's how to do the K thing... this one's a bit simpler:

Number.prototype.k = function () {
    // We don't want any thousands processing if the number is less than 1000.if (this < 1000) {
        // edit 2 May 2013: make sure it's a string for consistencyreturnthis.toString();
    }
    // Round to 100s first so that we can get the decimal point in there// then divide by 10 for thousandsvar thousands = Math.round(this / 100) / 10;
    // Now convert it to a string and add the kreturn thousands.toString() + 'K';
};

Call this in the same way: var num = 2000; num.k()

Solution 2:

Theoretically, yes.

As TimWolla points out, it requires a lot of logic.

Ruby on Rails have a helper for presenting time with words. Have a look at the documentation. The implementation for that code is found on GitHub, and could give you some hint as how to go about implementing this.

I agree with the comment to reduce the complexity by choosing one format.

Hope you find some help in my answer.

Post a Comment for "Javascript Convert Numbers To Different Formats Or String Alternative"