Math.floorは切り捨て、Math.ceilは切り上げ、Math.absは絶対値という仕組みを上手く利用します。正規関数/^[1-9][0-9]*$/も使用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | <!DOCTYPE html> <html lang= "ja" > <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0" > <title>割り勘電卓</title> <link rel= "stylesheet" href= "styles.css" > <style> body { font-size:16px; text-align: center; font-family: Arial, sans-serif; } h1 { font-size: 24px; } input[type= "text" ]{ padding: 7px; border: 1px solid #ddd; border-radius: 3px; width: 100px; font-weight: bold; font-size: 18px; text-align: right; } #btn { margin: 30px auto; width: 180px; border-radius: 5px; box-shadow: 0 4px 0 #e91b0c; background: #f44336; color: #fff; cursor: pointer; padding: 7px; } #btn:hover{ opacity: 0.8; } </style> </head> <body> <h1>割り勘電卓</h1> <p>金額 <input type= "text" id= "price" value= "0" > <p>人数 <input type= "text" id= "num" value= "0" > <div id= "btn" >計算する</div> <p id= "result" ></p> <script> ( function (){ 'use strict' ; var priceForm = document.getElementById( 'price' ); var numForm = document.getElementById( 'num' ); var btn = document.getElementById( 'btn' ); var result = document.getElementById( 'result' ); priceForm.addEventListener( 'click' , function (){ this .select(); }); numForm.addEventListener( 'click' , function (){ this .select(); }); btn.addEventListener( 'click' , function (){ var price = priceForm.value; var num = numForm.value; var x1, x2, y1, y2; var unit = 100; if (price.match(/^[1-9][0-9]*$/) && num.match(/^[1-9][0-9]*$/)){ if (price % num === 0){ result.innerHTML = '一人' +(price / num)+ '円丁度です!' ; } else { x1 = Math.floor(price / num / unit) * unit; y1 = price - (x1 * num); x2 = Math.ceil(price / num / unit) * unit; y2 = Math.abs(price - (x2 * num)); result.innerHTML = '一人' + x1 + '円だと' + y1 + '円足りません。<br>' + '一人' + x2 + '円だと' + y2 + '円余ります。' ; } } else { result.innerHTML = '入力された値に誤りがあります。' } }); })(); </script> </body> </html> |