LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptで小数点を切り捨て表示する方法

Posted at

画面上に消費税を表示する際に小数点を消したかったので、その解決方法をシンプルに書きます。

Math.floorを使用する

Math.floor(数値)と記述することで、()内の数値を小数点切り捨て表示することができます。
Math.floor(5.2)なら5が返ってきます。

使用例

price.js
const itemPrice = document.getElementById("item_price");
itemPrice.addEventListener("keyup", () => {
  tax = Math.floor(itemPrice.value * 0.1);

上記例では、入力フォームの要素をidで取得し、keyupによってキーボード操作時にイベント発火するようにしてあります。
フォームに入力された数値の10%(itemPrice.value * 0.1)をMath.floor()内に記述して小数点切り捨て表示できるようにしてあります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0