본문 바로가기
TIL/TIL

Math.floor(Math.random() * (max - min)) + min 범위 구하기.

by koreashowme 2020. 2. 15.
  • Math.random() generates a random number between 0 and 1 (not including 1).

  • You need to scale that value based on the range of numbers you want. Your range is how far from your min desired number to your max desired number which is max - min.

  • If you want to include the max value in the range of numbers generated, then use max - min + 1

  • You then need to make sure the random number starts at the right base rather than 0 so you add min to it.

  • Then, if you want it to be an integer you call Math.floor() to truncate it to the next lowest integer.


So, if you just had this:

Math.floor(Math.random())

You would always get zero. Because Math.floor() of a float value between 0 and 1 (not including one) will always truncate down to 0.

Then, if you expand the range with:

Math.floor(Math.random() * (max - min + 1))

You would now get a random number between 0 and max - min including the larger value.

So, to then get it to start at the right base, you add in min like this:

Math.floor(Math.random() * (max - min + 1)) + min

 

 

https://stackoverflow.com/questions/17516771/javascript-random-number

'TIL > TIL' 카테고리의 다른 글

Delete local storage data  (0) 2020.02.17
새로운 데이터 값 id 주기 JSON, array.length + 1  (0) 2020.02.16
회원가입 DOM, form validation 설계  (0) 2020.02.14
Element 담긴 내용 불러오기  (0) 2020.02.14
Adding Event Handler  (0) 2020.02.14

comment