用js实现收银功能。
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>xx超市收银系统</title> 5 <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> 6 </script> 7 <script type="text/javascript"> 8 $(function () { 9 $('form').submit(function () { 10 var payable = Number($('#txtPayable').val());//应付 11 var payment = Number($('#txtPayment').val());//实付 12 if (payable === payment) { 13 $('#tdPocket').text(0); 14 } else if (payable > payment) { 15 $('#tdPocket').text('您还需再支付' + (payable*10 - payment*10)/10 + '元!'); 16 } else {//需要找零 17 var yuan = [100, 50, 20, 10, 5, 1]; 18 var jiao = [5, 2, 1]; 19 var msg = ''; 20 var payableYuan = parseInt(payable); 21 var paymentYuan = parseInt(payment); 22 var pocketYuan = paymentYuan - payableYuan;//找零元 23 var surplus = pocketYuan; 24 $(yuan).each(function() { 25 if (surplus >= this) { 26 var count = parseInt(surplus / this); 27 msg += this + '元' + count + '张'; 28 surplus -= count * this; 29 } 30 }); 31 //在js中10.2-10.1=0.09999999999999964,防止小数误差,需要*10 32 var pocketJiao = parseInt(((payment * 10) - (payable * 10)) - (pocketYuan * 10));//找零角 33 surplus = pocketJiao; 34 $(jiao).each(function () { 35 if (surplus >= this) { 36 var count = parseInt(surplus / this); 37 msg += this + '角' + count + '张'; 38 surplus -= count * this; 39 } 40 }); 41 msg += '共' + pocketYuan + '.' + pocketJiao + '元'; 42 $('#tdPocket').text(msg); 43 } 44 return false; 45 }); 46 }); 47 </script> 48 <style type="text/css"> 49 table { 50 border: 1px solid #0000cd; 51 } 52 53 td { 54 padding: 2px; 55 } 56 57 .right { 58 text-align: right; 59 } 60 61 .left { 62 text-align: left; 63 width: 50px; 64 } 65 66 .center { 67 text-align: center; 68 } 69 </style> 70 </head> 71 <body> 72 <form> 73 <table border="1" cellpadding="0" cellspacing="0"> 74 <tr> 75 <td class="right">应付:</td> 76 <td class="left"><input type="number" id="txtPayable" min="0" step="any" /></td> 77 </tr> 78 <tr> 79 <td class="right">实付:</td> 80 <td class="left"><input type="number" id="txtPayment" min="0" step="any" /></td> 81 </tr> 82 <tr> 83 <td class="right">找零:</td> 84 <td class="left" id="tdPocket"></td> 85 </tr> 86 <tr> 87 <td colspan="2" class="center"><input type="submit" value="计算" id="btnCalc" /></td> 88 </tr> 89 </table> 90 </form> 91 </body> 92 </html>
效果
样式有点丑,没时间去调。
找零时,从最大面值的钱开始找,找零5.1,找一张5元,而不是找5张1元。
只考现行的第五套人民币面值,不考虑分币,目前几乎不怎么流通分币了。
重点是算出零钱该找出x张y面值的钱,由于js对于小数计算有误差,需要先将小数换算成整数,再转成小数.
js中10.2-10.1结果是0.09999999999999964;
要想得到结果0.1,笨一点的办法(10.2*10-10.1*10)/10=0.1;
有了这款神器,是不是再也不用担心找错钱了?我还是比较喜欢收银员给我多找点钱:)
如果觉得对你有帮助,请点个赞,谢谢!
不足与错误之处,敬请批评指正!