繁体   English   中英

一个 If 语句,用于查找数字字段是否留空或有太多小数位,但如果只有小数位为零则忽略

[英]An If statement that finds if a number field is left blank or has too many decimal places but ignores if only zeroes in decimal places

我有这一行代码:

if ($val === "" || ($val.split(".")[1] || "").length > 2)

感谢这里的好人的一些帮助。 但是这行代码即使数字都是零,也会计算超过 2 个小数位的数字。

问题是人们可以加上 2.00,这很好,但不能加上 2.000,这是相同的数字。 所以我想再添加一个 || 允许人们添加多个零小数位的语句。

整个代码是这样的:

$(document).ready(function() {
  $("#submitCalculation").click(function() {
    $(".checkLength").each(function() {
      $val = $(this).val();
      if ($val === "" || ($val.split(".")[1] || "").length > 2) {    
        $(this).popover({
          html: true, 
          placement: "bottom",  
          content: '<textarea class="popover-textarea"></textarea>',
          template: '<div class="popover"><div class="arrow"></div>'+
              '<div class="row"><div class="col-3 my-auto"><i class="fas fa-exclamation-triangle" id="invalid-input7">'+
              '</i></div><div class="popover-content col-9">Enter a value between 2 and 50 m with up to 2 decimal places.'+
              '</div></div>' 
        });
        $(this).popover("show");
        $(this).click( function() {
            $(this).popover("hide");
        });
      }
    })
  })
}) 

它检查数字输入的有效性,如果该字段为空,则弹出窗口告诉他们并且脚本在那里停止。 如果该字段有太多小数位,poppver 会告诉他们并且脚本在那里停止。 但是,现在的问题在于人们可以添加多个零小数位,脚本并没有停止,但是弹出窗口仍然弹出。

期待您在这方面的帮助,这让我困扰了一段时间。

在检查之前将数字转换为浮点数,因为这将丢弃小数点后的尾随零。 然后使用正则表达式检查小数点后是否有太多数字。 您还可以使用isNaN来检查它是否根本不是数字。

 $(document).ready(function() { $("#submitCalculation").click(function() { $(".checkLength").each(function() { const $val = $(this).val(); let valid = true; const valFloat = parseFloat($val); if (isNaN(valFloat)) { valid = false; } else if (/\\.\\d{3}/.test(valFloat.toString())) { valid = false; } if (!valid) { console.log("Invalid input"); } else { console.log("Valid input"); } }) }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="checkLength"> <button id="submitCalculation">Check</button>

这应该可以完成这项工作:

 console.log("my answer:","1.2345,0.0103,4.56,2.3400,123.22000,234" .split(",").map(val=>{ let m=val.match(/\\.\\d\\d(.*)/); return val+': '+!!(m&&m[1]>0) }) ); // the following is Barmar's method which gets it wrong in 4 cases: console.log("Barmar's answer:","1.2345,0.0103,4.56,2.3400,123.22000,234" .split(",").map(val=> val+': '+!!(val == "" || val.match(/\\.\\d{0,2}[1-9]+/))) );

在您的脚本中,您需要替换

$val = $(this).val(); 
if ($val === "" || ($val.split(".")[1] || "").length > 2) { ...

$val = $(this).val(); 
let m=$val.match(/\.\d\d(.*)/);
if (!!(m&&m[1]>0)) { ...

暂无
暂无

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

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