JavaScript Math object

JavaScript Math Object

The Math object is used to perform common mathematical calculations in JavaScript.

Different from String and Date objects, the Math object is not a class of the object and does not have a constructor Math(), so there is no need to create a Math object and you can use the Math object directly. Similarly, the methods in the Math object are also static methods and can be used directly through Math.function.

Math object properties

JavaScript provides 8 properties of the Math object, representing some commonly used arithmetic values:


AttributesDescription


Math.E Arithmetic constant e, the base of natural logarithms (approximately equal to 2.718)

Math .LN2 The natural logarithm of 2 (approximately equal to 0.693)

Math.LN10 The natural logarithm of 10 (approximately equal to 2.302)

Math.LOG2E The logarithm of e with base 2 ( Approximately equal to 1.414)

Math.LOG10E The logarithm of e based on base 10 (approximately equal to 0.434)

Math.PI Pi (approximately equal to 3.14159)

Math. SQRT1_2 The reciprocal of the square root of 2 (approximately equal to 0.707)

Math.SQRT2 The square root of 2 (approximately equal to 1.414)

Use the properties of Math

The above properties of the Math object can be used directly:

    php中文网(php.cn)  

Run this example, the output is:

3.141592653589793

Arithmetic method

In addition to the arithmetic values that can be accessed by the Math object, there are several functions (methods) that can be used.

The following example uses the round method of the Math object to round a number.

document.write(Math.round(4.7));

The output of the above code is:

5

The following example uses the random() method of the Math object to return a random number between 0 and 1:

document.write(Math.random()) ;

The output of the above code is:

0.897235837765038

The following example uses the floor() method and random() of the Math object to return a random number between 0 and 11:

document.write(Math.floor(Math.random()*11));

The output of the above code is:

2

Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!