Today we will figure out how to format a number utilizing JavaScript or jQuery. I was taking a shot at a report when I need the add up to be formatted and after some seeking on web I discovered some plugins however I would prefer not to use plugin on my website for such a little errand. At long last I've discovered strategy which works for me so I've chosen to compose a post to impart these little strategies to every one of you. Here I am sharing two strategies so it's your decision to use anybody of them which is appropriate for you.
Function 1 :-//-----------------Apply comma formation on Amount using JavaScript ------------------
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
Function 2:-
This Function take string as parameter and by using jQuery .test() function and regular expression we are adding comma to the amount.i.e. 2000 will become 2,000
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
No comments:
Post a Comment