Format numbers in JavaScript similar to C#

后端 未结 18 2302
傲寒
傲寒 2020-11-22 12:26

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString(\"format_provider\") or

18条回答
  •  一个人的身影
    2020-11-22 12:54

    Here's a simple JS function to add commas to an integer number in string format. It will handle whole numbers or decimal numbers. You can pass it either a number or a string. It obviously returns a string.

    function addCommas(str) {
        var parts = (str + "").split("."),
            main = parts[0],
            len = main.length,
            output = "",
            first = main.charAt(0),
            i;
    
        if (first === '-') {
            main = main.slice(1);
            len = main.length;    
        } else {
            first = "";
        }
        i = len - 1;
        while(i >= 0) {
            output = main.charAt(i) + output;
            if ((len - i) % 3 === 0 && i > 0) {
                output = "," + output;
            }
            --i;
        }
        // put sign back
        output = first + output;
        // put decimal part back
        if (parts.length > 1) {
            output += "." + parts[1];
        }
        return output;
    }
    

    Here's a set of test cases: http://jsfiddle.net/jfriend00/6y57j/

    You can see it being used in this previous jsFiddle: http://jsfiddle.net/jfriend00/sMnjT/. You can find functions that will handle decimal numbers too with a simple Google search for "javascript add commas".

    Converting a number to a string can be done many ways. The easiest is just to add it to a string:

    var myNumber = 3;
    var myStr = "" + myNumber;   // "3"
    

    Within, the context of your jsFiddle, you'd get commas into the counter by changing this line:

    jTarget.text(current);
    

    to this:

    jTarget.text(addCommas(current));
    

    You can see it working here: http://jsfiddle.net/jfriend00/CbjSX/

提交回复
热议问题