Format numbers in JavaScript similar to C# Format numbers in JavaScript similar to C# jquery jquery

Format numbers in JavaScript similar to C#


Yes, there is definitely a way to format numbers properly in javascript, for example:

var val=2489.8237val.toFixed(3) //returns 2489.824 (round up)val.toFixed(2) //returns 2489.82val.toFixed(7) //returns 2489.8237000 (padding)

With the use of variablename.toFixed .

And there is another function toPrecision() .For more detail you also can visit

http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html


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/