Math.floor inJavaScript?

  • The `Math.floor()` function in JavaScript is used to round a number down to the nearest integer. This means that it will always round towards negative infinity.

JavaScript
Math.floor(x)
  • Syntax
  • – **x**: A number
JavaScript
 console.log(Math.floor(5.95)); // 5
  console.log(Math.floor(5.05)); // 5
  console.log(Math.floor(5));   // 5
  console.log(Math.floor(-5.05));// -6
JavaScript

  // Rounding down an array of numbers
  const numbers = [4.7, 3.2, 7.8, -2.5, -8.9];
  const flooredNumbers = numbers.map(num => Math.floor(num));
  console.log(flooredNumbers); // [4, 3, 7, -3, -9]
  
JavaScript

  // Getting the quotient of a division
  const dividend = 10;
  const divisor = 3;
  const quotient = Math.floor(dividend / divisor);
  console.log(quotient); // 3
  

`Math.floor()` is especially useful when you need to ensure that the result of a calculation is rounded down to the nearest whole number, such as when calculating positions, array indices, or pagination.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *