LoginSignup
0
1

More than 1 year has passed since last update.

【JavaScript】数値の四捨五入や切り下げ、切り上げ

Last updated at Posted at 2022-02-09

JavaScriptにおける数値の四捨五入や切り下げ、切り上げについてメモしておく。

数値の四捨五入や切り上げ、切り捨て

四捨五入

四捨五入には、Math.round()を使用する。Math.round()は、数値を四捨五入してもっとも近似の整数を返す。

const value = Math.round(3.14159);    // 3
const value = Math.round(3.51389);    // 4

// 任意の桁で四捨五入(小数第3位の場合)
const value = Math.round(3.14159 * 100) / 100; // 3.14

切り下げ

数値の切り下げには、Math.floor()を使用する。

const value = Math.floor(3.14159);    // 3

// 任意の桁で切り下げ(小数第3位の場合)
const value = Math.floor(3.14159 * 100) / 100;    // 3.14

ただし、負の値にMath.floor()を使うと切り下げ、つまり与えた数値以下の最大の整数を返すため下記のサンプルのようになる。
単に小数点以下を削除したい場合は、Math.trunc()を使用する。

// Math.floor()
const value = Math.floor(-3.623);    // -4

// Math.trunc()
const value = Math.trunc(-3.623);    // -3

切り上げ

数値の切り上げには、Math.ceil()を使用する。

const value = Math.ceil(3.14159);    // 4

// 任意の桁で切り上げ(小数第3位の場合)
const value2 = Math.ceil(3.14159 * 100) / 100;    // 3.15

これも負の場合について、切り上げ、つまり数値以上の最小の整数が返されるので、-3.14159の場合は-3が返される。

0
1
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
1