LoginSignup
1
1

More than 5 years have passed since last update.

Math.floorを使わないで小数点以下を切り捨てる

Last updated at Posted at 2015-11-23

0〜9のランダムな整数を出力

(1)Math.floorを使う方法


var res = Math.floor(Math.random() * 10 ); //0〜9

(2)ビット演算子を2つ書く方法


var res = ~~(Math.random() * 10 ); //0〜9

●ソースコードみててチルダ2つあるのなんぞ?と調べて「なるほど」と思いメモ。

//----<追記>-----//

(3)コメントにて教えていただいた方法(hikaru_oao様ありがとうございました!)


var res = (Math.random() * 10 )|0; //0〜9

※注意点:
(2)の~~を使う方法は条件によってはMath.floorと結果の値が変わるとの情報をいただきました(jkr_2255様ありがとうございました!)

1
1
3

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