Javascript将数字转换为不同的格式或字符串替代 [英] Javascript Convert numbers to different formats or string alternative

查看:64
本文介绍了Javascript将数字转换为不同的格式或字符串替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新:

使用javascript或jQuery,如何将数字转换为其不同的变体:

Using javascript or jQuery, how can I convert a number into it's different variations:

例如:

1000000 来...

1000000 to...

1,000,000 or 1000K

OR

1000 来...

1000 to...

1,000 or 1K

OR

1934和1234 来...

1934 and 1234 to...

1,934 or -2K (under 2000 but over 1500)

1,234 or 1k+  (over 1000 but under 1500)

这可以在函数中完成吗?

Can this is done in a function?

希望这很有道理.

C

推荐答案

您可以向Number.prototype添加方法,例如:

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 exists
    if (decimalPart.length > 2) {
        decimalPart = decimalPart.substring(2);
    } else {
        // Otherwise remove it altogether
        decimalPart = '';
    }
    // Work through the digits three at a time
    var i = intPart.length - 3;
    while (i > 0) {
        intPart = intPart.substring(0, i) + ',' + intPart.substring(i);
        i = i - 3;
    }
    return intPart + decimalPart;
};

现在您可以将其称为var num = 1000; num.addCommas(),它将返回"1,000".那只是一个例子,但是您会发现创建的所有函数都将涉及在过程中尽早将数字转换为字符串,然后处理并返回字符串. (将整数和小数部分分开可能会特别有用,因此您可能希望将其重构为自己的方法.)希望这足以使您入门.

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.

这是做K事情的方法……这有点简单:

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 consistency
        return this.toString();
    }
    // Round to 100s first so that we can get the decimal point in there
    // then divide by 10 for thousands
    var thousands = Math.round(this / 100) / 10;
    // Now convert it to a string and add the k
    return thousands.toString() + 'K';
};

以相同的方式调用它:var num = 2000; num.k()

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

这篇关于Javascript将数字转换为不同的格式或字符串替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆