Monday, 18 November 2013

Currency format utility method in Sencha Touch 2

In my project, i am looking for currency format function in Sencha Touch similar to Ext Js Ext.util.Format.currency method. But Sencha Touch doesn't support this currency format method by default. So with the help of Ext Js Code, i created my own currency format utility function for Sencha Touch.

Let's see the currency format utility method implementation

Ext.define('MyApp.utils.Functions', {
    singleton: true,
    currencyPrecision: 2,
    currencySign: '$',
    currencyAtEnd: false,
    decimalSeparator: '.',
    thousandSeparator: ',',

    currency: function (v, currencySign, decimals, end) {
        var negativeSign = '',
            format = ",0",
            i = 0;
        v = v - 0;
        if (v < 0) {
            v = -v;
            negativeSign = '-';
        }

        decimals = Ext.isDefined(decimals) ? decimals : MyApp.utils.Functions.currencyPrecision;

        format += format + (decimals > 0 ? '.' : '');
        for (; i < decimals; i++) {
            format += '0';
        }

        v = MyApp.utils.Functions.formatValue(v);

        if ((end || MyApp.utils.Functions.currencyAtEnd) === true) {

            return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || MyApp.utils.Functions.currencySign);

        } else {

            return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || MyApp.utils.Functions.currencySign, v);

        }
    },

    formatValue: function (nVal) {

        nVal += '';
        x = nVal.split(MyApp.utils.Functions.decimalSeparator);
        x1 = x[0];
        x2 = x.length > 1 ? MyApp.utils.Functions.decimalSeparator + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + MyApp.utils.Functions.thousandSeparator + '$2');
        }
        return x1 + x2;
    }
});

In order to access the currency format function, you need to pass the amount as first parameter followed by currency sign as second parameter. Third parameter is the decimal precision and fourth parameter will display currency sign next to amount.Here is the utility access code

var currency = MyApp.utils.Functions.currency('100','$');
console.log("currency= "+currency);

You can also pass amount with decimal values. here is the code

var currency = MyApp.utils.Functions.currency('100.55','$');
console.log("currency= "+currency);
//output: currency= $100.55

This currency format function also support thousand separator. you need to use the below code

var currency = MyApp.utils.Functions.currency('10000.55','$');
console.log("currency= "+currency);
//output: currency= $10,000.55

Please feel free to customize this utility method based on your needs. Hope, you enjoyed this Post
.

No comments:

Post a Comment