Html script math floor

Math

The Math namespace object contains static properties and methods for mathematical constants and functions.

Math works with the Number type. It doesn’t work with BigInt .

Description

Unlike most global objects, Math is not a constructor. You cannot use it with the new operator or invoke the Atomics object as a function. All properties and methods of Math are static.

Note: Many Math functions have a precision that’s implementation-dependent.

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

Static properties

Euler’s number and the base of natural logarithms; approximately 2.718 .

Natural logarithm of 10 ; approximately 2.303 .

Natural logarithm of 2 ; approximately 0.693 .

Base-10 logarithm of E ; approximately 0.434 .

Base-2 logarithm of E ; approximately 1.443 .

Ratio of a circle’s circumference to its diameter; approximately 3.14159 .

Square root of ½; approximately 0.707 .

Square root of 2 ; approximately 1.414 .

The initial value of the @@toStringTag property is the string «Math» . This property is used in Object.prototype.toString() .

Static methods

Returns the absolute value of x .

Returns the arccosine of x .

Returns the hyperbolic arccosine of x .

Returns the hyperbolic arcsine of a number.

Returns the arctangent of x .

Returns the arctangent of the quotient of its arguments.

Returns the hyperbolic arctangent of x .

Returns the cube root of x .

Returns the smallest integer greater than or equal to x .

Returns the number of leading zero bits of the 32-bit integer x .

Returns the hyperbolic cosine of x .

Returns e x , where x is the argument, and e is Euler’s number ( 2.718 …, the base of the natural logarithm).

Returns subtracting 1 from exp(x) .

Returns the largest integer less than or equal to x .

Returns the nearest single precision float representation of x .

Returns the square root of the sum of squares of its arguments.

Returns the result of the 32-bit integer multiplication of x and y .

Returns the natural logarithm (㏒e; also, ㏑) of x .

Returns the base-10 logarithm of x .

Returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x .

Returns the base-2 logarithm of x .

Returns the largest of zero or more numbers.

Читайте также:  Bootstrap modal

Returns the smallest of zero or more numbers.

Returns base x to the exponent power y (that is, x y ).

Returns a pseudo-random number between 0 and 1 .

Returns the value of the number x rounded to the nearest integer.

Returns the sign of the x , indicating whether x is positive, negative, or zero.

Returns the hyperbolic sine of x .

Returns the positive square root of x .

Returns the hyperbolic tangent of x .

Returns the integer portion of x , removing any fractional digits.

Examples

Converting between degrees and radians

The trigonometric functions sin() , cos() , tan() , asin() , acos() , atan() , and atan2() expect (and return) angles in radians.

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

function degToRad(degrees)  return degrees * (Math.PI / 180); > function radToDeg(rad)  return rad / (Math.PI / 180); > 

Calculating the height of an equilateral triangle

If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

An equilateral triangle where a perpendicular of one edge is drawn from the opposite vertex, forming a right triangle with three sides marked as

In JavaScript, we can do this with the following:

We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians.

Returning a random integer between two bounds

This can be achieved with a combination of Math.random() and Math.floor() :

function random(min, max)  const num = Math.floor(Math.random() * (max - min + 1)) + min; return num; > random(1, 10); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 26, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Math.floor()

The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.

Try it

Syntax

Parameters

Return value

The largest integer smaller than or equal to x . It’s the same value as -Math.ceil(-x) .

Description

Because floor() is a static method of Math , you always use it as Math.floor() , rather than as a method of a Math object you created ( Math is not a constructor).

Examples

Using Math.floor()

.floor(-Infinity); // -Infinity Math.floor(-45.95); // -46 Math.floor(-45.05); // -46 Math.floor(-0); // -0 Math.floor(0); // 0 Math.floor(4); // 4 Math.floor(45.05); // 45 Math.floor(45.95); // 45 Math.floor(Infinity); // Infinity 

Decimal adjustment

In this example, we implement a method called decimalAdjust() that is an enhancement method of Math.floor() , Math.ceil() , and Math.round() . While the three Math functions always adjust the input to the units digit, decimalAdjust accepts an exp parameter that specifies the number of digits to the left of the decimal point to which the number should be adjusted. For example, -1 means it would leave one digit after the decimal point (as in «× 10 -1 «). In addition, it allows you to select the means of adjustment — round , floor , or ceil — through the type parameter.

It does so by multiplying the number by a power of 10, then rounding the result to the nearest integer, then dividing by the power of 10. To better preserve precision, it takes advantage of Number’s toString() method, which represents large or small numbers in scientific notation (like 6.02e23 ).

/** * Adjusts a number to the specified digit. * * @param type The type of adjustment. * @param value The number. * @param exp The exponent (the 10 logarithm of the adjustment base). * @returns The adjusted value. */ function decimalAdjust(type, value, exp)  type = String(type); if (!["round", "floor", "ceil"].includes(type))  throw new TypeError( "The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.", ); > exp = Number(exp); value = Number(value); if (exp % 1 !== 0 || Number.isNaN(value))  return NaN; > else if (exp === 0)  return Math[type](value); > const [magnitude, exponent = 0] = value.toString().split("e"); const adjustedValue = Math[type](`$magnitude>e$exponent - exp>`); // Shift back const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e"); return Number(`$newMagnitude>e$+newExponent + exp>`); > // Decimal round const round10 = (value, exp) => decimalAdjust("round", value, exp); // Decimal floor const floor10 = (value, exp) => decimalAdjust("floor", value, exp); // Decimal ceil const ceil10 = (value, exp) => decimalAdjust("ceil", value, exp); // Round round10(55.55, -1); // 55.6 round10(55.549, -1); // 55.5 round10(55, 1); // 60 round10(54.9, 1); // 50 round10(-55.55, -1); // -55.5 round10(-55.551, -1); // -55.6 round10(-55, 1); // -50 round10(-55.1, 1); // -60 // Floor floor10(55.59, -1); // 55.5 floor10(59, 1); // 50 floor10(-55.51, -1); // -55.6 floor10(-51, 1); // -60 // Ceil ceil10(55.51, -1); // 55.6 ceil10(51, 1); // 60 ceil10(-55.59, -1); // -55.5 ceil10(-59, 1); // -50 

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

Math . floor ( ) , Math . round ( ) , Math . ceil ( ) и Math . trunc ( )

Объект Math содержит набор методов, который используется для округления чисел:

  • round ( ) — округление по обычным правилам;
  • floor ( ) — округление вниз;
  • ceil ( ) — округление вверх;
  • trunc ( ) — отбрасывание дробной части, не обращая внимания на знак аргумента.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Для обычного округления используйте Math . round ( ) :

 console.log(Math.round(15.52))// 16 console.log(Math.round(15.3))// 15 console.log(Math.round(15.52)) // 16 console.log(Math.round(15.3)) // 15      

Округление до ближайшего целого в большую сторону — Math . ceil ( ) :

 console.log(Math.ceil(15.52))// 16 console.log(Math.ceil(15.3))// 16 console.log(Math.ceil(15.52)) // 16 console.log(Math.ceil(15.3)) // 16      

Округление до ближайшего целого в меньшую сторону — Math . floor ( ) :

 console.log(Math.floor(15.52))// 15 console.log(Math.floor(15.3))// 15 console.log(Math.floor(15.52)) // 15 console.log(Math.floor(15.3)) // 15      

🛠 Используйте осторожно при работе с отрицательными числами:

 console.log(Math.floor(-15.3))// -16 console.log(Math.floor(-15.3)) // -16      

Так происходит потому что -16 меньше, чем -15, а округление происходит в меньшую сторону.

Отбрасывание дробной части — Math . trunc ( )

 console.log(Math.trunc(15.52))// 15 console.log(Math.trunc(-15.3))// -15 console.log(Math.trunc(0.123))// 0 console.log(Math.trunc(-0.123))// -0 console.log(Math.trunc(15.52)) // 15 console.log(Math.trunc(-15.3)) // -15 console.log(Math.trunc(0.123)) // 0 console.log(Math.trunc(-0.123)) // -0      

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Разные виды округления нужны в разных ситуациях:

  • когда нужно разбить данные на страницы и посчитать общее количество страниц, используйте округление вверх: const total Pages = Math . ceil ( total Items / items Per Page ) .
  • когда нужно выбрать случайный элемент массива, используйте округление вниз: Math . floor ( Math . random ( ) * array . length ) .

Источник

JavaScript Math.floor()

The Math.floor() method rounds a number DOWN to the nearest integer.

JavaScript Rounding Functions

Syntax

Parameters

Return Value

Browser Support

Math.floor() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью