javascript 消費税込みの価格を求める
- 作成日 2020.12.17
- 更新日 2022.07.28
- javascript
- javascript
javascriptで、消費税込みの価格を計算するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
計算
以下のコードで計算することが可能です。ここでは消費税10%で計算してます。
// 消費税10%
const TAX = 10;
// 商品価格 + ( 商品価格 ✖ 税率 ) 端数は四捨五入
function total(price, tax) {
return Math.round(price * (1 + tax / 100));
}
console.log(total(1000, TAX)); // 1100
関数をアロー関数で記述すると以下のようになります。
// 消費税10%
const TAX = 10;
// 商品価格 + ( 商品価格 ✖ 税率 ) 端数は四捨五入
const total = (price, tax) => Math.round(price * (1 + tax / 100))
console.log(total(1000, TAX)) // 1100
サンプルコード
以下は、
「計算」ボタンをクリックすると、税込価格を計算する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
<link rel="stylesheet"
href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css">
</head>
<style>
.main {
margin: 0 auto;
margin-top: 200px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 30px;
}
</style>
<script>
// 消費税10%
const TAX = 10;
// 商品価格 + ( 商品価格 ✖ 税率 ) 端数は四捨五入
const total = (price, tax) => Math.round(price * (1 + tax / 100))
const hoge = () => {
// 価格を取得
let kakaku = price.value;
// 税込み価格を計算
let result = total(kakaku,TAX);
// pathを表示
foo.textContent = result;
}
</script>
<body>
<div class="main">
<h2 id="foo" class="badge badge-primary">税込み価格を計算</h2>
<div class="form-group">
<label for="formGroupExampleInput" class="bmd-label-floating">価格</label>
<input id="price" type="number" class="form-control">
</div>
<button onclick="hoge();" type="button" class="btn btn-raised btn-danger">
計算
</button>
</div>
</body>
</html>
計算結果が表示されていることが確認できます。
-
前の記事
php fgetsでファイルの内容を1行ずつ読み込む 2020.12.17
-
次の記事
Alpine.jsを使ってモーダルを作成する 2020.12.17
コメントを書く