简体   繁体   English

在计算字段中防止多个小数点

[英]Prevent multiple decimals points in calculation field

I have a JavaScript calculator which uses the following code to handle decimal points in the calculation input field (also below): 我有一个JavaScript计算器,它使用以下代码来处理计算输入字段中的小数点(也在下面):

$('#button-dot').click(function() {
var lastChar = $('#disp').val().slice(-1);
var firstChar = $('#disp').val().slice(0);
if ($('#disp').hasClass("result")) {
      $('#disp').removeClass("result").val("");
      addChar(this.form.display,'0' + '.');
    }
else if (lastChar == '.'){
    // DO NOTHING
    }
else if (lastChar == '1' || lastChar == '2' || lastChar == '3' || lastChar == '4' || lastChar == '5' || lastChar == '6' || lastChar == '7' || lastChar == '8' || lastChar == '9' || lastChar == '0' && firstChar != '0'){
    addChar(this.form.display,'.');
    }
else if (firstChar == '0'){
    addChar(this.form.display,'0' + '.');
    }
else {
  addChar(this.form.display,'0' + '.');
  }
  $('#disp').removeClass("result");
});

where the addChar function is given by: 其中的addChar函数由以下形式给出:

function addChar(input, character) {
  if (input.value == null || input.value == "0" ) {
    input.value = character
    }
  else {
    input.value += character
    }
};

and the input field: 和输入字段:

<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>

I want to enhance my code in such a way as to restrict users from entering multiple decimals in the same number (as seen below), while still allowing multiple decimals in the calculation string (also below): 我想通过限制用户输入相同数字的多个小数(如下所示)的方式来增强我的代码,同时仍允许计算字符串中的多个小数(也如下所示):

Avoid this - 避免这种情况-

在此处输入图片说明

But allow this - 但是允许这个-

在此处输入图片说明

I have looked into regex as I understand the solution to my problem may involve it somehow, but I am not sure how to implement it (my JavaScript skills are still a work in progress!). 我了解了问题的解决方案可能会涉及到regex ,但是我不确定如何实现它(我的JavaScript技能仍在开发中!)。

I also thought of splitting the string with any of the operands ( -,+,/,*,% ) and checking each element of the resulting array for a decimal point, but I am thinking that might be a tad messy. 我还考虑过用任何操作数( -,+,/,*,% )分割字符串,并检查结果数组的每个元素是否有小数点,但我认为这可能有点混乱。

Any ideas? 有任何想法吗?

I would make a counter variable and then add one to it every time you come across a . 我将创建一个计数器变量,然后在每次遇到时将其添加一个. , while resetting to zero every time you find an operand. ,而每次找到操作数时都重置为零。 That way, if your counter is any more than one at the end of the for loop, than you can alert the user to get rid of the dot. 这样,如果您的计数器在for循环结束时不止一个,那么您就可以提醒用户摆脱点的困扰。

Pseudo-code: 伪代码:

// Do this input.length - 1 times:

// store current char in var curChar.
// check if curChar is a dot. If it is, counter++
// check if curChar is an operand. If it is, counter = 0.

// After the for loop, check if counter is 1 or 0. If it is either of  
// these, the user entered an acceptable input. Otherwise, they need to 
// take out the extra dots.

You could easily do this with a single regular expression: 您可以使用单个正则表达式轻松完成此操作:

^(?:(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[-+/*%]|$))+$

Explanation 说明

 ^                      # Begin of string
 (?:                    # Group
      (?:                    #  A number
           \d+ 
           (?: \. \d* )?
        |  \. \d+ 
      )
      (?:
           [-+/*%]                # Operator
        |                       # or, 
           $                      # EOS
      )
 )+                     # End group, do 1 to many times
 $                      # End of string

Yup, you can use the following regex to validate user input: 是的,您可以使用以下正则表达式来验证用户输入:

^\d+(\.\d+)?([+\-*\/]\d+(\.\d+)?)*$
  • \\d+(\\.\\d+)? matches a decimal 匹配小数
  • [+\\-*\\/] matches the operators [+\\-*\\/]匹配运算符

regex101 regex101

 $('#disp').on('input', function() { if (this.value.match(/^\\d+(\\.\\d+)?([+\\-*\\/]\\d+(\\.\\d+)?)*$/)) { $('#status').show(); } else { $('#status').hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/> <span id="status">OK</span> 

You could trigger an error function if the input string matches \\d\\.\\d+\\. 如果输入字符串匹配\\d\\.\\d+\\.则可能触发错误函数\\d\\.\\d+\\. - that's a digit followed by a decimal place, then 1 or more digits followed by another decimal point. -这是一个数字,后跟小数点,然后是1个或多个数字,后跟另一个小数点。 If there is anything other than a digit after the first decimal point (such as an operator), the error will not trigger. 如果第一个小数点后没有数字(例如运算符),则不会触发错误。

regex101 regex101

So I added a counter: 所以我加了一个计数器:

dotCount = 0;

And did this for the button-dot function and the operands: 并对button-dot函数和操作数执行了以下操作:

$('#button-dot').click(function() {
var lastChar = $('#disp').val().slice(-1);
var firstChar = $('#disp').val().slice(0);

if (dotCount == 0){
    if ($('#disp').hasClass("result")) {
      $('#disp').removeClass("result").val("");
      addChar(this.form.display,'0' + '.');
    }
    else if (lastChar == '.'){
        // DO NOTHING
    }
    else if (lastChar == '1' || lastChar == '2' || lastChar == '3' || lastChar == '4' || lastChar == '5' || lastChar == '6' || lastChar == '7' || lastChar == '8' || lastChar == '9' || lastChar == '0' && firstChar != '0'){
        addChar(this.form.display,'.');
    }
    else if (firstChar == '0'){
        addChar(this.form.display,'0' + '.');
    }
    else {
        addChar(this.form.display,'0' + '.');
    }
}// END OF dotCount == 0

else if (dotCount == 1){
    //DO NOTHING
}
  $('#disp').removeClass("result");
  dotCount = 1;
});

(using + as an example): (以+为例):

$('#button-plus').click(function() {
var lastChar = $('#disp').val().slice(-1);
var firstChar = $('#disp').val().slice(0);
if (lastChar == '*' || lastChar == '-' || lastChar == '+' || lastChar == '/' || lastChar == '.' || lastChar == '(' || lastChar == '%'){
    // DO NOTHING
    }
else if (firstChar == '0'){
    // DO NOTHING
    }
else {
  addChar(this.form.display, '+');
  }
  $('#disp').removeClass("result");
  dotCount = 0;
});

Works like a charm! 奇迹般有效! Thanks, Kai Christensen for the counter idea. 谢谢,凯·克里斯滕森(Kai Christensen)提出了反主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM