一, 由于 javascript float 数据相乘时得到错误数据,这里使用函数过滤
<script> $(function(){ $('#number0').blur(function(){ num = $('#number0').val(); if(!isNaN(num)){ scale = $('#scale0').val(); $('#cny0').val(accMul(num,scale)); } }); }); function accMul(arg1,arg2) { var m=0,s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(".")[1].length}catch(e){} try{m+=s2.split(".")[1].length}catch(e){} return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) } </script>
二,这里通过函数来控制文本框小数点后面的位数
<script> function badFloat(num, size){ if(isNaN(num)) return true; num += ''; if(-1 == num.indexOf('.')) return false; var f_arr = num.split('.'); if(f_arr[1].length > size){ return true; } return false; } // 格式化小数 //@f float 传入小数: 123; 1.1234; 1.000001; //@size int 保留位数 //@add bool 进位: 0 舍 1 进 function formatfloat(f, size, add){ f = parseFloat(f); if(size == 2) conf = [100,0.01]; if(size == 3) conf = [1000,0.001]; if(size == 4) conf = [10000,0.0001]; if(size == 5) conf = [100000,0.00001]; if(size == 6) conf = [1000000,0.000001]; if(size == 7) conf = [10000000,0.0000001]; if(size == 8) conf = [100000000,0.00000001]; var ff = Math.floor(f * conf[0]) / conf[0]; if(add && f > ff) ff += conf[1]; return isNaN(ff)? 0: ff; } function vNum(o, len){ if($("#buy_price").val()!="" && $("#buy_num").val()!=""){ if(badFloat(o.value, len)) o.value=formatfloat(o.value,len,0); var ci = $("#buy_price").val()*$("#buy_num").val(); $("#buy_money").text(Math.round(ci*100)/100); } } </script>
调用时这样调用:
onkeyup="vNum(this,2);" TODO:第二种 Jquery 的小数点验证可以替换为, <form action="/example/html5/demo_form.asp" method="get"> Points: <input type="number" name="points" min="2" step="0.01" /> <input type="submit" /> </form>
这种事 HTML5 新属性,同样可以实现限制小数点位数的问题。