Set Currency Format based on User Settings through JavaScript

If you are working on a custom HTML web resource which displays different currency formats for different countries and regions, there comes a need to set the currency format according to user settings in CRM. In this tutorial we’ll learn how to format the currency accordingly.

First of all retrieve Number Separator,Decimal Symbol, Currency Decimal Precision and Currency Symbol from User Settings of logged in user through SDK REST as shown in the code below.


var NumberSeparator = "";
var DecimalSymbol = "";
var CurrencyDecimalPrecision = "";
var CurrencySymbol = "";

function retrieveUserSettings() {
 var userId = Xrm.Page.context.getUserId();
 userId = userId.replace(/[{}]/g, "");
 SDK.REST.retrieveRecord(userId, "UserSettings", "CurrencyDecimalPrecision,NumberSeparator,DecimalSymbol,CurrencySymbol", null, retrieveUserSettingsCallBack, getErrors);
}
function retrieveUserSettingsCallBack(result) {
 NumberSeparator = result.NumberSeparator;
 DecimalSymbol = result.DecimalSymbol;
 CurrencyDecimalPrecision = result.CurrencyDecimalPrecision;
 CurrencySymbol = result.CurrencySymbol;
}
function getErrors(error) {
 alert(error.message);
}

Now lets suppose if we want to format the Extended Amount of Invoice Products we’ll format it as given below

ExtendedAmount = Number(ExtendedAmount);
var ExtendedAmountFormatted = (ExtendedAmount).formatMoney(2, DecimalSymbol, NumberSeparator, CurrencySymbol);

And now the magic method which does all the formatting according to the parameters passed.


Number.prototype.formatMoney = function (c, d, t, CurrencySymbol) {
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return CurrencySymbol + s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

And you have the currency formatted according to User Settings.



Leave a Reply

*

code