JS 實作 #13 | 數字顯示優化;Math.abs()、toFixed()、正規表達式加千位逗號

這個章節要將顯示的數字 2971.831 優化為 + 2,971.83

開始實作

1. UI CONTROLLER 新增一個內部方法 formartNumber() ,用來處理 UI 上顯示的數字。

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    **var formatNumber = function(num, type) {
        
    };**

    return {
        ...
    };

})();

2. 原本 udemy 中的寫法如下

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    ****var formatNumber = function(num, type) {
      **var numSplit, int, dec, type;

        num = Math.abs(num); //傳回絕對值(Number)
        num = num.toFixed(2); //小數點以下二位四捨五入(string)

        numSplit = num.split('.'); //小數點前後拆開為二組

        int = numSplit[0];
        if (int.length > 3) {
            int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510,但此寫法沒處理到更多位數
        }

        dec = numSplit[1];

        return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec; //最後加總** 
    };

    return {
        ...
    };

})();

改為如下使用正規表達式

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    var formatNumber = function(num, type) {
      var numSplit, int, dec, type;

        num = Math.abs(num);
        num = num.toFixed(2);

        numSplit = num.split('.');

        **int = numSplit[0].replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,');**
        dec = numSplit[1];

        return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
    };

    return {
        ...
    };

})();

3. 最後將要顯示的數字先代入此 formatNumber() 方法即完成

// UI CONTROLLER
var UIController = (function() {

    var DOMstrings = {
        ...
    };

    var formatNumber = function(num, type) {
        var numSplit, int, dec, type;

        num = Math.abs(num);
        num = num.toFixed(2);

        numSplit = num.split('.');

        int = numSplit[0].replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,');

        dec = numSplit[1];

        return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
    };

    return {
        getInput: function() {
            ...
        },
        getDOMstrings: function() {
            return DOMstrings;
        },
        addListItem: function(obj, type) {

            ...

            // replace placholder text with soma actual data
            newHtml = html.replace('%id', obj.id);
            newHtml = newHtml.replace('%description%', obj.description);
            newHtml = newHtml.replace('%value%', **formatNumber(obj.value, type)**);

            // insert the HTML into the DOM
            document.querySelector(element).insertAdjacentHTML('beforeend',newHtml);
        },
        deleteListItems: function(selectorID) {
            var el = document.getElementById(selectorID);
            el.parentNode.removeChild(el);
        },
        clearFields: function () {
            var fields, fieldsArr;

            fields = document.querySelectorAll(DOMstrings.inputDescription + ', ' + DOMstrings.inputValue);
            fieldsArr = Array.prototype.slice.call(fields);

            fieldsArr.forEach(function(current, index, originalArray){
                current.value = "";
            });

            fieldsArr[0].focus();
        },
        displayBudget: function(obj) {
            **var type;
            obj.budget > 0 ? type = 'inc' : type = 'exp';**
            document.querySelector(DOMstrings.budgetLabel).textContent = **formatNumber(obj.budget, type)**;
            document.querySelector(DOMstrings.incomeLabel).textContent = **formatNumber(obj.totalInc, 'inc')**;
            document.querySelector(DOMstrings.expensesLabel).textContent = **formatNumber(obj.totalExp, 'exp')**;

            if (obj.percentage > 0 ) {
                document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
            } else {
                document.querySelector(DOMstrings.percentageLabel).textContent = '---';
            }
            
        },
        displayPercentages: function(percentages) {
           ...
        }
    };

})();

2020/04/06

Zeen is a next generation WordPress theme. It’s powerful, beautifully designed and comes with everything you need to engage your visitors and increase conversions.