CRM 2011 – Formatting a currency using Javascript

I was looking on LinkedIn and then I saw Jamie Miley had replied and then I found my way to his blog.  He had some interesting blog entries on his site.  I saw this one Formatting Currency in Microsoft Dynamics CRM 2011 and CRM 4 in JScript.  It was a nice function to format currencies in Javascript.

I though it was useful piece of Javascript although I wondered why you would need it in CRM because you cpuld just format the field.

Still I am always looking to improve my Javascript skills and I thought it was a good example.  also you never know they might be a day when I need to format soem currency using Javascript for reasons that are not clear to me.

//Format currency in CRM jscript

//EXAMPLE USAGE
//alert(FormatAsCurrency(10000));

function FormatAsCurrency(amount) {

var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
amount = s;
var delimiter = ","; // replace comma if other mark is 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;

 

}

2 thoughts on “CRM 2011 – Formatting a currency using Javascript

  1. Jamie Miley March 16, 2011 / 2:18 am

    Also as to why, since you asked. At my last job I was asked to format a text field (had to be text, don’t know why) to be a rollup of a bunch of sub entity values that represented currency. It was easier from a dev standpoint than working with CrmMoney I felt in some ways also.

    Also, I have found a couple forums where people have been trying to do exactly this but have found that most of the examples they found on the internet didn’t work with CRM Jscript, but were made for regular JScript.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s