LoginSignup
30
9

More than 3 years have passed since last update.

JavaScriptで整数除算演算子を実現する

Posted at

何をしたい?

割り算で小数点以下を切り捨てるようにしたい

javascriptでの割り算

JavaScriptで整数同士の割り算を行った場合小数点以下まで出力されてしまいます。
CやC++で整数同士の割り算を行った場合小数点以下は切り捨てられるようになっています。

console.log(23 / 10);
> 2.3

2.32と出力されるようにしたい

解決策1

Math.floor()を使用する。
参考: Math.floor()

console.log(Math.floor(23 / 10));
> 2

解決策2

ビット演算子| (ビットごとの OR)を使用する。
参考: Bitwise_OR

console.log(23 / 10 | 0);
> 2

ベンチマーク

パフォーマンスを求めた場合、ビット演算子を使用した方が早そうな感じはする(計測方法が間違ってたらごめんなさい)

const startTime1 = performance.now();
for(let num = 0; num < 100000; num ++) {
    console.log(Math.floor(23 / 10));
}
const endTime1 = performance.now();


const startTime2 = performance.now();
for(let num = 0; num < 100000; num ++) {
    console.log(23 / 10 | 0);
}
const endTime2 = performance.now();

console.log(`Math.floor(23 / 10): ${endTime1 - startTime1}`);
console.log(`23 / 10 | 0: ${endTime2 - startTime2}`);

// 1回目
> Math.floor(23 / 10): 1766.8149839937687
> 23 / 10 | 0:         1773.3923920094967

// 2回目
> Math.floor(23 / 10): 1794.4279589951038
> 23 / 10 | 0:         1724.0651339888573

// 3回目
> Math.floor(23 / 10): 1811.3405220210552
> 23 / 10 | 0:         1716.2479899823666
30
9
1

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
30
9