0

JS限制用户只能输入两位小数(允许正负数)

<br> <input name="amount" id="amount" theme="simple" /></p><p>document.getElementById('amount').onkeyup = function () {<br> changeNum(this);<br>}<br>
<br>function changeNum(obj) {<br> obj.value = obj.value.replace(/<sup id="fnref-1"><a href="#fn-1" class="footnote-ref">1</a></sup>/g, ""); //清除"数字"、"."、"+"、"-"号以外的字符</p><pre><code> obj.value = obj.value.replace(/^\./g, &quot;&quot;); //验证第一个字符是.字 //obj.value = obj.value.replace(/^[0]/g, &quot;&quot;);//验证第一个字符是0字 obj.value = obj.value.replace(/00/g, &quot;0&quot;); //验证第一个是多个0(只保留第一个0, 清除多余的0) obj.value = obj.value.replace(/\.{2,}/g, &quot;.&quot;); //只保留第一个&quot;.&quot;, 清除多余的 obj.value = obj.value.replace(/\-{2,}/g, &quot;-&quot;); //只保留第一个&quot;-&quot;, 清除多余的 obj.value = obj.value.replace(/\+{2,}/g, &quot;+&quot;); //只保留第一个&quot;+&quot;, 清除多余的 obj.value = obj.value.replace(/\+\-/g, &quot;+&quot;); //只保留第一个&quot;+&quot;, 清除多余的&quot;-&quot; obj.value = obj.value.replace(/\-\+/g, &quot;-&quot;); //只保留第一个&quot;-&quot;, 清除多余的&quot;+&quot; obj.value = obj.value.replace(/[0-9]+\+/g, &quot;&quot;); //数字后面不准许输入&quot;+&quot; obj.value = obj.value.replace(/[0-9]+\-/g, &quot;&quot;); //数字后面不准许输入&quot;-&quot; obj.value = obj.value.replace(/\.[0-9]*\+/g, &quot;.&quot;); //去除&quot;.&quot;号后面的&quot;+&quot; obj.value = obj.value.replace(/\.[0-9]*\-/g, &quot;.&quot;); //去除&quot;.&quot;号后面的&quot;-&quot; obj.value = obj.value.replace(&quot;.&quot;, &quot;$#$&quot;).replace(/\./g, &quot;&quot;).replace(&quot;$#$&quot;, &quot;.&quot;); obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数 </code></pre><p>}<br>

<br>//js限制只能输入两位小数,js输入金钱<br><input type="text" onkeyup="setnum(this)"/><br>

<br>function setnum(that) {<br> //只保留数字和点("."),其余的字符都去掉 <br> that.value = that.value.replace(/<sup id="fnref-2"><a href="#fn-2" class="footnote-ref">2</a></sup>/g, ""); <br> //只保留第一个点("."),有两个点(".")只保留一个<br> that.value = that.value.replace(/.{2,}/g, "."); <br> //把点(".")进行转换防止被正则表达式抹掉<br> that.value = that.value.replace(".", "$#$").replace(/./g, "").replace("$#$", ".");<br> //限制只能输入两位小数 <br> that.value = that.value.replace(/^(-)<em>(\d+).(\d\d).</em>$/, '$1$2.$3');<br> if (that.value.indexOf(".") &lt; 0 && that.value != "") {//限制首位不能是0</p><pre><code> that.value = parseFloat(that.value);</code></pre><p>}<br>}</p><p>


  1. \d+.-
  2. \d.