+ 2
How convert string to money format?
How can i convert string number like '2500000' to money format (2,500,000) in javascript?
3 odpowiedzi
+ 2
I just realised you mean with commas. Firstly note that adding commas would make the number a string.
Try this.
function commas(num){
var digits = num.toString().split("");
var count = 0;
for (var x = digits.length - 1; x >= 0; x--){
count++;
if (count === 3){
digits[x] = "," + digits[x];
count = 0;
}
}
return digits.join("");
}
alert(commas(2500000));
+ 1
in which language
- 1
There is no "money format" as such in JavaScript. The best variable for money would simply be a number. The Number() method converts to a number.
var moneyString = "5000";
var moneyNumber = Number(moneyString);
A regular number value can be manipulated with operators (+ - * /) in the same way that a "money value" can be.
moneyNumber += 1000;
The only difference is possibly is you want to add currency units. Adding units would convert it back into a string, so best do it last.
var money = "quot; + moneyNumber;
//Now money stores "$6000".