JavaScript:格式化输入法给出了错误的值

时间:2016-04-13 18:30:00

标签: javascript jquery input

我在JavaScript / JQuery中编写一个方法,用于转换用户在输入框中输入的值。意思是使这个输入区域意识到。 该功能包含在开头删除零,放置千位分隔符和小数分隔符。

在此用例中,符号为千位分隔符,点为小数点分隔符

例如,以下输出后面的输入被转换。

  • 12300 => 12,300.00
  • 100 => 100.00
  • 1023.456 => 1,023.456

现在数字还有问题,不到100。 例如,以下输入格式错误:

  • 1 => 1,0.00
  • 2.05 => 0.05
  • 20 => 20,0.00
  • 25.65 => 0.65

当我没有在输入框中输入小数值时,我得到一个不需要的千位分隔符。当我输入小数值时,我在小数分隔符之前丢失了我的内容。

代码:

$("#queryInstructedAmountFrom").change(function(){
                        var amount = $("#queryInstructedAmountFrom").val();
                        amount = removeZeros(amount);
                        var nonFractions = amount.match(/.{1,3}/g);
                        if(nonFractions == null) {
                            nonFractions = [];
                            nonFractions.push(amount);
                        }

                        var splittedValues = amount.split(/[,.]/);
                        amount = "";

                        if(splittedValues.length == 1) {
                            amount += splittedValues[0];
                            nonFractions = amount.match(/.{1,3}/g);
                            var firstIndex = amount.length % 3;
                            if(firstIndex != 0) {
                            var firstNumbers = amount.substr(0, firstIndex);
                            amount = amount.substr(firstIndex);
                            nonFractions = amount.match(/.{1,3}/g);

                            if(nonFractions == null) {
                                nonFractions = [];
                                nonFractions.push(amount);
                            }

                            amount = "";

                            amount += firstNumbers;
                            amount += thousandSeparator;
                            } else {
                                amount = "";
                            }



                            for(var i=0 ; i < nonFractions.length ; i++) {
                                amount += nonFractions[i];

                                if(i < (nonFractions.length - 1) && nonFractions.length != 1){
                                    amount += thousandSeparator;
                                }
                            }

                            amount += decimalSeparator;
                            amount += "00";
                        } else {
                            for(var i=0 ; i < splittedValues.length - 1 ; i++) {
                                amount += splittedValues[i];
                            }

                            nonFractions = amount.match(/.{1,3}/g);
                            var firstIndex = amount.length % 3;
                            if(firstIndex == 0) {
                                nonFractions = amount.match(/.{1,3}/g);
                            }

                            if(firstIndex >= 1 && nonFractions != null) {
                                var firstNumbers = amount.substr(0, firstIndex);
                                amount = amount.substr(firstIndex);
                                nonFractions = amount.match(/.{1,3}/g);

                                if(nonFractions != null) {
                                    amount = "";
                                    amount += firstNumbers;
                                    amount += thousandSeparator;
                                } else {
                                    nonFractions = [];
                                    nonFractions.push(amount);
                                }
                            } else {

                                amount = "";
                            }


                            for(var i=0 ; i < nonFractions.length ; i++) {
                                amount += nonFractions[i];

                                if(i < (nonFractions.length - 1) && nonFractions.length != 1){
                                    amount += thousandSeparator;
                                }
                            }

                            amount += decimalSeparator;
                            amount += splittedValues[splittedValues.length -1];
                        }

        $("#queryInstructedAmountFrom").val(amount);
      });
    });

function removeZeros(amount) {
            while (amount.charAt(0) === '0') {
                amount = amount.substr(1);
           }

           if(amount.length == 0){
            amount = "0";
           }
            return amount;
        }

出了什么问题?

3 个答案:

答案 0 :(得分:0)

为什么不使用jQuery-Mask-Plugin

<input type="text" id="money" />

并只调用插件:

$('#money').mask('000.000.000.000.000,00', {reverse: true});

Plunker:https://plnkr.co/edit/PY7ihpS3Amtzeya9c6KN?p=preview

答案 1 :(得分:0)

请参阅以下代码更新。

$(document).ready(function() {
    $("#queryInstructedAmountFrom").change(function() {
        var amount = $("#queryInstructedAmountFrom").val();
        amount = removeZeros(amount);
        
        // format amount using 'ThousandFormattedValue' function
        amount = ThousandFormattedValue(amount);

        $("#queryInstructedAmountFrom").val(amount);
    });

});

function removeZeros(amount) {
    while (amount.charAt(0) === '0') {
        amount = amount.substr(1);
    }

    if (amount.length == 0) {
        amount = "0";
    }
    return amount;
}

function ThousandFormattedValue(iValue) {
    // declaring variables and initializing the values
    var numberArray, integerPart, reversedInteger, IntegerConstruction = "",
        lengthOfInteger, iStart = 0;

    // splitting number at decimal point by converting the number to string
    numberArray = iValue.toString().split(".");

    // get the integer part
    integerPart = numberArray[0];

    // get the length of the number
    lengthOfInteger = integerPart.length;

    // if no decimal part is present then add 00 after decimal point
    if (numberArray[1] === undefined) {
        numberArray.push("00");
    }


    /* split the integer part of number to individual digits and reverse the number
        ["4" , "3" , "2" , "1"] - after split
        ["1" , "2" , "3" , "4"] - after reverse
        "1234" - after join     
    */
    reversedInteger = integerPart.split("").reverse().join("");


    // loop through the string to add commas in between
    while (iStart + 3 < lengthOfInteger) {

        // get substring of very 3 digits and add "," at the end
        IntegerConstruction += (reversedInteger.substr(iStart, 3) + ",");

        // increase counter for next 3 digits
        iStart += 3;
    }


    // after adding the commas add the remaining digits 
    IntegerConstruction += reversedInteger.substr(iStart, 3);


    /* now split the constructed string and reverse the array followed by joining to get the formatted number
        ["1" , "2" , "3" , "," ,"4"] - after split
        ["4" , "," , "3" , "2" , "1"] - after reverse
        "4,321" - after join
    */
    numberArray[0] = IntegerConstruction.split("").reverse().join("");

    // return the string as Integer part concatinated with decimal part
    return numberArray.join(".");
}

答案 2 :(得分:0)

  
    

出了什么问题?

  

我几乎说了一切。你有非常不清楚,凌乱的代码,我几乎没有遵循你的逻辑,但你在代码中有几个关键的逻辑错误,例如:

<强> 1

1转换为1,.00因为:

var splittedValues = amount.split(/[,.]/);

使用单个元素[&#39; 1&#39;]

创建数组
var firstIndex = amount.length % 3;

1%3 == 1,所以你进入if条件,其中amount += thousandSeparator;附加千位分隔符,但只有在你之后有东西时才应该添加分隔符

<强> 2

2.05是错误的,因为它进入了这个分支:

var firstNumbers = amount.substr(0, firstIndex); // stores '2' into firstNumbers
amount = amount.substr(firstIndex); // sets amount to empty string

之后,nonFractions为null:

nonFractions = [];
nonFractions.push(amount);

但是根本没有使用firstNumbers,即它的值丢失了

第3

另外,你有:

    nonFractions = amount.match(/.{1,3}/g);
    var firstIndex = amount.length % 3;
    if (firstIndex == 0) {
        nonFractions = amount.match(/.{1,3}/g);
    }

nonFractions重新初始化的意义是什么?

可能有更多的错误和边缘情况,这些代码失败,我建议您使用库(如在其他答案中)或如果您想拥有自己的代码,这里是您可以使用的简单版本:

&#13;
&#13;
$(document).ready(function() {
    $("#queryInstructedAmountFrom").change(function() {
        var val = parseFloat(('0' + $("#queryInstructedAmountFrom").val()).replace(/,/g, '')); // convert original text value into float
        val = ('' + (Math.round(val * 100.0) / 100.0)).split('.', 2);
        if (val.length < 2) val[1] = '00'; // handle fractional part
        else while (val[1].length < 2) val[1] += '0';
        var t = 0;
        while ((val[0].length - t) > 3) { // append thousand separators
            val[0] = val[0].substr(0, val[0].length - t - 3) + ',' + val[0].substr(val[0].length - t - 3);
            t += 4;
        }
        $("#queryInstructedAmountFrom").val(val[0] + '.' + val[1]);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="queryInstructedAmountFrom">
&#13;
&#13;
&#13;