What other JavaScript Math methods can I use?

Question

What other JavaScript Math methods can I use?

Answer

There are many JavaScript Math methods! Here are some of the ones you’ll use and see often:

  • Math.ceil(number) will return the smallest integer that is greater than or equal to the number passed in
  • Math.floor(number) will return the largest integer that is less than or equal to the number passed in
  • Math.max(x, y, z, ...) will return the highest value number in a set of given numbers (comma separated numbers, not in an array)
  • Math.min(x, y, z, ...) will return the lowest value number in a set of given numbers (comma separated numbers, not in an array)
  • Math.random() * maxNum will return a floating-point number between 0 and up to, but not including, the maxNum number
  • Math.round(number) will return the value of the number passed in rounded to the nearest whole number
4 Likes

:cowboy_hat_face:

const numImaginaryFriends = (friends) => {

    let imaginaryFriends = Math.ceil((friends * 25) / 100);

    return imaginaryFriends;

}

console.log(numImaginaryFriends(20)) // Should print 5

console.log(numImaginaryFriends(10)) // Should print 3 (2.5 rounded up!)
2 Likes

A more concise method:

const numImaginaryFriends = totalFriends => {
return Math.ceil(toltalFriends * 0.25);
}

console.log(numImaginaryFriends(20)) // Should print 5
console.log(numImaginaryFriends(10)) // Should print 3 (2.5 rounded up!)

2 Likes

and after small refactoring: :wink:

const numImaginaryFriends = (num) => Math.ceil(num * 0.25);

1 Like

You don’t need brackets around num as there’s only one argument passed in the function:

const numImaginaryFriends = num => Math.ceil(num * 0.25)

4 Likes