முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 2 · பாடம் 3 இன் 4பாடத்திட்டத்தில் 7/32~10 min
தொகுதி பாடங்கள் (3/4)

எண்கள் மற்றும் கணிதம்

In JavaScript there is only one numeric type: number. Both integers and decimals (floating point) live in there. No separate int / float like in other languages.

JS
typeof 42; // 'number'
typeof 3.14; // 'number'
typeof -0.001; // 'number'
typeof Infinity; // 'number'   ← Infinity is a special number
typeof NaN; // 'number'   ← even "Not a Number" is a number (!)

The global Math object

Math is not a function: it is an object with useful methods and constants. You don't instantiate it, you use it directly:

JS
Math.min(3, 1, 7); // 1
Math.max(3, 1, 7); // 7
Math.abs(-5); // 5
Math.round(4.5); // 5
Math.floor(4.9); // 4   (always rounds down)
Math.ceil(4.1); // 5   (always rounds up)
Math.sqrt(16); // 4
Math.pow(2, 10); // 1024   (equivalent to 2 ** 10)
Math.PI; // 3.141592653589793

Random numbers

Math.random() returns a decimal between 0 (included) and 1 (excluded). To get an integer in a range you use a small formula:

JS
// Random integer between 0 and 9
Math.floor(Math.random() * 10);

// Random integer between 1 and 6 (a six-sided die)
Math.floor(Math.random() * 6) + 1;

The pains of decimals (floating point)

JS uses the IEEE-754 64-bit representation, shared with almost all languages. It is a binary representation, so some decimals can't be represented exactly:

JS
0.1 + 0.2; // 0.30000000000000004 (!)
0.1 + 0.2 === 0.3; // false

Standard solution: round with toFixed(n) (which returns a string) or use integers in cents/thousandths when working with money:

JS
(0.1 + 0.2).toFixed(2); // '0.30' (string)
Number((0.1 + 0.2).toFixed(2)); // 0.3 (number)

Try it

உடற்பயிற்சி#js.m2.l3.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Compute the area of a circle with radius `r = 5` rounded to two decimal places, as a `number`. For `r=5` 78.54 is expected.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Math.PI for pi, ** for exponentiation; .toFixed(2) to round, Number(...) to convert back to a number.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m2.l3.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Given three numbers 12, 7, 23, return as the last expression the difference between the max and the min (i.e. 16).

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Math.max and Math.min accept multiple comma-separated arguments.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்