js金錢轉換為小額的功能

admin發表於2017-04-17

有時候需要將一個較大金額的錢換算為較小金額的。

下面的這段程式碼就實現了這樣的功能,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style media="screen">
.main {
  width: 400px;
  height: 400px;
  margin: auto;
  padding: 20px;
}
.denomination {
  width: 100px;
  height: 30px;
  margin-bottom: 10px;
}
.exchange {
  height: 40px;
}
.rmb {
  width: 150px;
  border: 1px solid rgb(99,184,255);
}
.half, .twenty, .ten, .five, .one {
  width: 100px;
  height: 20px;
  margin-top: 10px;
  margin-left: 8px;
}
</style>
</head>
<body>
  <div class="main">
    <input class="denomination" type="text" name="name" value="">
    <input class="exchange" type="button" name="name" value="兌換">
    <div class="rmb">
      <div class="half">
        50元:
      </div>
      <div class="twenty">
        20元:
      </div>
      <div class="ten">
        10元:
      </div>
      <div class="five">
        5元:
      </div>
      <div class="one">
        1元:
      </div>
    </div>
  </div>
</body>
<script>
  var denom = document.querySelector('.denomination');
  var exchange = document.querySelector('.exchange');
  var half = document.querySelector('.half');
  var twenty = document.querySelector('.twenty');
  var ten = document.querySelector('.ten');
  var five = document.querySelector('.five');
  var one = document.querySelector('.one');
  exchange.onclick = exchangeMoney;
  function exchangeMoney() {
    a = denom.value;
    var reg = /^\d+$/;
    if (reg.test(a) == true) {
      M50 = parseInt(a / 50);
      M20 = parseInt((a % 50) / 20);
      M10 = parseInt((a % 50 % 20) / 10);
      M5 = parseInt((a % 50 % 20 % 10) / 5);
      M1 = a % 50 % 20 % 10 % 5;
      half.innerHTML = '50元:' + M50 + '張';
      twenty.innerHTML = '20元:' + M20 + '張';
      ten.innerHTML = '10元:' + M10 + '張';
      five.innerHTML = '5元:' + M5 + '張';
      one.innerHTML = '1元:' + M1 + '張';
    } else if (a.length == 0) {
      alert('請輸入金額');
    } else {
      alert('內容必須是整數數字');
    }
  }
</script>
</html>

相關文章