总和中逗号的放置不正确

时间:2016-10-06 14:07:35

标签: javascript jquery

我有一个表,每行都有一个文本输入。用户可以在每个文本框中指定一个美元金额。我的代码循环遍历每个文本输入,并简单地总结值。我的问题是当用户输入超过> = 1,000,000的值时,总和变得不正确。例如,当用户输入1,000,000时,总和为1,000。

function init_icheck() {
    $('#datatable input[type=checkbox]').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        increaseArea: '10%'
    });
}

// When Pay in Full Checkbox is Checked fill in Pay This Time Field with Invoice Amount Due Value
function paynow() {
    var payFull = $('input[type="checkbox"].payfull');
    payFull.on('ifChecked', function(event) {
        $(this).parents('tr').find('.paynow').val($(this).val().replace('$', ''));
        CalcFooter();
    });
}

// If Pay in Full Unchecked then remove value from respective Pay This Time Input
// Only bind the ifUnchecked event if the checkbox is checked
function remove_checkbox() {
    var payFull = $('input[type="checkbox"].payfull');
    payFull.on('ifUnchecked', function(event) {
        if ($(this).parents('tr').find('.paynow').val() == $(this).val().replace('$', '')) {
            $(this).parents('tr').find('.paynow').val('');
            CalcFooter();
        }
    });
}

// If Pay This Time changes recalculate total
function recalc_total() {
    $('.paynow').keyup(function() {
        var $ThisCheck = $(this).parents('tr').find('.payfull');
        // Add Commas if # is over 1,000
        $(this).val(addCommas($(this).val().replace(/,/g, '')));
        if ($(this).val() == $ThisCheck.val().replace('$', '')) {
            $ThisCheck.iCheck('check');
        } else {
            $ThisCheck.iCheck('uncheck');
        }
        CalcFooter();
    });
}


// Recalc Function
function CalcFooter() {
    var amtPage = 0;
    var amtTotal = 0;

    var Sum = 0;
    $('.paynow').each(function(index, Obj) {
        var value = parseFloat($(this).val().replace(',', ''));
        if (!isNaN(value)) amtPage += value;
    });

    $('#datatable').DataTable().$('.paynow').each(function(index, Obj) {
        var value = parseFloat($(this).val().replace(',', ''));
        if (!isNaN(value)) amtTotal += value;
    });

    $('#amounttopay').text(
        'Page: $' + addCommas(amtPage.toFixed(2)) +
        ' / Total: $' + addCommas(amtTotal.toFixed(2))
    );
}

// Add Commas if value > 1,000
addCommas = function(input) {
    // If the regex doesn't match, `replace` returns the string unmodified
    return (input.toString()).replace(
        // Each parentheses group (or 'capture') in this regex becomes an argument 
        // to the function; in this case, every argument after 'match'
        /^([-+]?)(0?)(\d+)(.?)(\d+)$/g,
        function(match, sign, zeros, before, decimal, after) {
            // Less obtrusive than adding 'reverse' method on all strings
            var reverseString = function(string) {
                return string.split('').reverse().join('');
            };
            // Insert commas every three characters from the right
            var insertCommas = function(string) {
                // Reverse, because it's easier to do things from the left
                var reversed = reverseString(string);
                // Add commas every three characters
                var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');
                // Reverse again (back to normal)
                return reverseString(reversedWithCommas);
            };
            // If there was no decimal, the last capture grabs the final digit, so
            // we have to put it back together with the 'before' substring
            return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
        }
    );
};

// Reinitialize iCheck on Pagination Change
$('#datatable').on('draw.dt', function() {
    init_icheck();
    paynow();
    recalc_total();
    remove_checkbox();
    CalcFooter();
});

// Initialize Datatables
$('#datatable').dataTable({
    "stateSave": true,
    "oLanguage": {
        "sSearch": "Search Results:"
    }
}); 

我有一个简单的jsfiddle来说明这个问题。我提前感谢你指出我正确的方向。

http://jsfiddle.net/tgf59ezr/14/

1 个答案:

答案 0 :(得分:3)

使用.replace(',', '')仅替换搜索到的字符串的第一个实例,导致数字解析无法按预期工作。

请改用:

.replace(/,/g, '')

g表示替换所有实例。

http://jsfiddle.net/da03j0aa/

参考:String.prototype.replace()