用逗号计算输出的数字

时间:2016-09-30 21:13:54

标签: javascript jquery html jquery-calculation

我有一个我正在构建的计算应用程序,并且我有输入显示逗号的地方,并且尽管使用逗号仍然可以运行计算,但现在我无法使用千位分隔符显示输出逗号。我几乎尝试了所有我能想到的东西。有人能告诉我我可能会离开的地方。

这是我的剧本:

    jQuery( document ).ready( function( $ ) {
            // SHOW OUTPUT DIV ONLY WHEN ALL FIELDS ARE COMPLETED
            $( '#calc-top' ).bind( 'keyup change', function() {
                var orderAmount = $( '#orderAmt' ).val().replace( '', ',' );
                if ( orderAmount !== "" && $( "#duration option:selected" ).val() !== "" && $( "#debitFreq option:selected" ).val() !== "" ) {
                    $( 'div#calc-bottom' ).css( 'display', 'block' );
                } else {
                    $( 'div#calc-bottom' ).css( 'display', 'none' );
                }
            } );
        } );

    jQuery(document).ready(function($){
        $("#orderAmt").keyup(function(event) {
            // skip for arrow keys
            if (event.which >= 37 && event.which <= 40) {
                event.preventDefault();
            }
            var $this = $(this);
            var num = $this.val().replace(/,/gi, "");
            var num2 = num.split(/(?=(?:[0-9]{3})+$)/).join(",");
            console.log(num2);
            // the following line has been simplified. Revision history contains original.
            $this.val(num2);
        });
        });
      // end jQuery

        // CALCULATE USER INPUT AND WRITE OUTPUT TO HTML ELEMENTS
        function calculate() {
            var orderAmt = parseFloat(document.getElementById( "orderAmt" ).value.replace(/,/g, ''));
            var duration = document.getElementById( "duration" ).value || 0;
            var debitFreq = document.getElementById( "debitFreq" ).value || 0;
            var outputAmt = document.getElementById( 'outputAmt' ) || 0;
            var numPayments = document.getElementById( 'numPayments' ) || 0;

            // CALCULATE NUMBER OF PAYMENTS
            if ( debitFreq == 7 ) {
                numPayments = Math.floor( duration / 7 );
            } else if ( debitFreq == 30 ) {
                numPayments = Math.floor( duration / 30 );
            }
            document.getElementById( 'numPayments' ).innerHTML = numPayments;

            // CALCULATE PAYMENT AMOUNT
            var stepA = (orderAmt / numPayments);
            var stepB = Math.floor( (((15 / 1000) * (duration / 360)) * 12) * orderAmt ) || 0;
            var stepC;
            if ( debitFreq == 7 ) {
                stepC = 0.10;
                //} else if (debitFreq == 30) {
                //stepC = 0.05;
            } else {
                stepC = 0;
            }
            var stepD = 0;
            //if ((duration == 30) && (debitFreq == 30)) {
            //stepD = 0.05;
            //} else {
            //stepD = 0;
            //}
            var stepE = stepC - stepD;
            var stepF = Math.floor( (((15 / 1000) * (duration / 360)) * 12) * orderAmt ) || 0;
            var stepG = Math.ceil( stepE * stepF );
            var stepH = stepB - stepG;
            var stepI = stepH / numPayments;
            var monthlyPayments = stepI + stepA;
            outputAmt.innerHTML = monthlyPayments.toFixed( 2 ) || 0;

            // OUTPUT WILL SHOW CORRECT DEBIT FORMATS BASED ON USER INPUT (i.e. 'week', 'weeks', 'month', 'months')
            var outputDefault1;
            if ( document.getElementById( "debitFreq" ).value == 7 ) {
                outputDefault1 = "week";
            } else if ( document.getElementById( "debitFreq" ).value == 30 ) {
                outputDefault1 = "month";
            }
            document.getElementById( "outputTerm1" ).innerHTML = outputDefault1;

            var outputDefault2;
            if ( document.getElementById( "debitFreq" ).value == 7 ) {
                outputDefault2 = "weeks";
            } else if ( document.getElementById( "debitFreq" ).value == 30 ) {
                outputDefault2 = "months";
            }
            document.getElementById( "outputTerm2" ).innerHTML = outputDefault2;

        }
        // end calculate function

        // ONLY ALLOW NUMERIC INPUT, NO ALPHA OR SPECIAL CHARACTERS EXCEPT COMMAS
        function isNumberKey( evt ) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode( key );
            var regex = /^[0-9.,]+$/;
            if ( !regex.test( key ) ) {
                theEvent.returnValue = false;
                if ( theEvent.preventDefault ) {
                    theEvent.preventDefault();
                }
            }
        }

        // TRIGGER EVENTS WHEN THE USER ENTERS DATA
        var userinputNum = document.getElementById( "orderAmt" );
        userinputNum.oninput = calculate;
        userinputNum.onkeypress = isNumberKey;

        var userinputDays = document.getElementById( "duration" );
        userinputDays.onchange = calculate;

        var userinputFreq = document.getElementById( "debitFreq" );
        userinputFreq.onchange = calculate;

这是我的小提琴:http://jsfiddle.net/qo5b7z93/

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

试试这个:

注意:出于可读性/可理解性的目的,以下函数非常冗长。您可能希望将其简化为生产

你会改变 outputAmt.innerHTML = monthlyPayments.toFixed( 2 ) || 0
- &GT; outputAmt.innerHTML = placeCommas(monthlyPayments);

function placeCommas(number) {
  if (number !== null && number !== undefined) {
    number = number.toFixed(2);
    var splitNum = number.split(".");
    var num = splitNum[0];
    var decimals = splitNum[1];

    var numArr = num.split("").reverse();
    var commaArr = [];
    for (var i = 0; i < numArr.length; i++) {
      commaArr.push(numArr[i]);
      if (i !== numArr.length - 1 && i % 3 === 2) {
        commaArr.push(",");
      }
    }
    num = commaArr.reverse().join("");
    number = num + "." + decimals;
    return number;
  }
}
console.log(placeCommas(0));
console.log(placeCommas(10));
console.log(placeCommas(100));
console.log(placeCommas(1000));
console.log(placeCommas(10000));
console.log(placeCommas(100000));
console.log(placeCommas(1000000));
console.log(placeCommas(10000000));
console.log(placeCommas(100000000));
console.log(placeCommas(1000000000));

答案 1 :(得分:0)

请看一下这个updated FIDDLE,我认为这应该做你需要的。

function FormatNumber(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var pattern = /(\d+)(\d{3})/;
    while (pattern.test(x1)) {
        x1 = x1.replace(pattern, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

答案 2 :(得分:0)

阻止使用箭头键,甚至任何键都不是那么用户友好。您的限制也消除了使用shift-arrow选择文本的可能性,以使用退格键删除输入。当他们用鼠标移动光标位置时,一旦键入,光标就会翻转到最后。这是异常行为,会让用户感到沮丧。

让他们输入他们想要的东西,并在他们退出输入框时进行清理。这更加用户友好。

因此我建议仅在焦点离开输入字段时应用数字格式,并在焦点再次进入时立即删除所有格式。

这里还有一个正则表达式replace,可以一次性应用格式:

$(this).val()
    .replace(/[^\d.]/gi, "") // clean-up
    .replace(/\B(\d{3})(?=(?:\d{3})*(?:\.|$))/g, ',$1'); // format

这是updated fiddle