Format numbers in JavaScript similar to C#
Solution 1:
Generally
- Formatting numbers in JavaScript
- Formatting numbers for currency display and more.
In jQuery
- autoNumeric (a decent number formatter & input helper with locale support for jQuery 1.5+)
- jQuery Format (a clientSide implementation of Java's SimpleDateFormat and NumberFormat)
- jquery-numberformatter (number formatter with locale support)
Solution 2:
Yes, there is definitely a way to format numbers properly in javascript, for example:
var val=2489.8237
val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.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
Solution 3:
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/