javascript にて切り上げ、切り捨て、四捨五入を扱う

Math オブジェクト

  • round ... 四捨五入
  • ceil ... 切り上げ
  • floor ... 切り下げ
let i = 1.7

console.log(Math.round(i))
console.log(Math.ceil(i))
console.log(Math.floor(i))

console.log("=========")

i = 1.4

console.log(Math.round(i))
console.log(Math.ceil(i))
console.log(Math.floor(i))
2
2
1
=========
1
2
1

小数点以下を扱う

let depth = function (d) {
	let res = 1
	for (i = 0; i < d; i++) {
		res = res * 10
	}
	return res
}

let log = function (i, d) {
	console.log("=========")
	console.log(Math.round(i * d) / d)
	console.log(Math.ceil(i * d) / d)
	console.log(Math.floor(i * d) / d)
}

log(1.748, depth(0))
log(1.748, depth(1))
log(1.748, depth(2))
=========
2
2
1
=========
1.7
1.8
1.7
=========
1.75
1.75
1.74
カテゴリー:js