Home > Web Front-end > JS Tutorial > body text

Math Namespace & BigInt

DDD
Release: 2024-09-13 22:19:32
Original
477 people have browsed it

Math Namespace & BigInt

Math.sqrt i.e sqrt is a part of Math namespace.

// 2 ways to get square root.
Math.sqrt(100); // 10, Method 1
100*(1/2); // 10, Method 2
8
*(1/3); // 2, works for cubic root also

Math.max() & Math.min():

Math.max(23,54,12,6,32,98,87,34,11); // 98
// Does type coercion also
Math.min(23,54,12,'6',32,98,87,34,11); // 6
// Does not do parsing
Math.min(23,54,12,'6px',32,98,87,34,11); // NaN

Inbuilt constants on Math object:

Math.PI * (Number.parseFloat('10px')**(2)); // Getting area

Generate a no b/w 1-6:

Math.trunc(Math.random() * 6) + 1;

Generatate a random no b/w an upper-lower limit:

const randomInt = (min, max) => Math.floor(Math.random() * (max-min)) + 1 + min;
randomInt(10,20);

// All of these Math.method() do type coercion.
Math.trunc(25.4); // 25
Math.round(25.4); // 25
Math.floor(25.4); // 25
Math.ceil(25.4); // 26

Math.floor is a better choice for negative numbers.

Math.trunc(-25.4); // -25
Math.floor(-25.4); // -26

// Rounding decimals: .toFixed returns a string, not a number
(2.5).toFixed(0); // '3'
(2.5).toFixed(3); // '2.500'
(2.345).toFixed(2); // '2.35'

// Add a unary + sign to convert it to a no.
+(2.345).toFixed(2); // 2.35

// Number is a primitive, hence they don't have methods. SO behind the scene, JS will do boxing, i.e transform primitive into a no object, perform the operation and then when operation is finished, transform it back to primitive.

Modular or Remainder Operator:

5 % 2; // 1

8 % 3; // 2
8 / 3; // 2.6666666666666665

// Odd or Even
const isEven = n => n%2 === 0;
isEven(20);
isEven(21);
isEven(22);

Usecase: Used to work with all odd rows, even rows, nth time etc.

Numeric Separators: [ES2021]

Used for representing really large numbers
These are underscores which can be placed between numbers. The engine ignores these underscores, its reduces the confusion for devs.
Ex. const diameter = 287_460_000_000;
diameter; // 287460000000

const price = 342_25;
price; // 34225

const fee1 = 1_500;
const fee2 = 15_00;
fee1 === fee2; // true

Underscore can be placed ONLY between numbers.
It cannot be placed adjacent to a dot of decimal.
It also cannot be placed at the begining or the end of the no.

const PI = 3.14_15;
PI; // 3.1415

All are invalid example of numeric separators

const PI = 3.1415; // Cannot be placed in the begining.
const PI = 3.1415
; // Cannot be placed in the end.
const PI = 3_.1415; // Cannot be placed adjacent to a decimal dot.
const PI = 3.1415; // Cannot be placed adjacent to a decimal dot.
const PI = 3.
_1415; // Two in a row cannot be placed.

Converting Strings to Numbers:

Number('2500'); // 2500
Number('25_00'); // NaN , Hence we can only use when directly numbers are assigned to a variable. Hence, if a no is stored in the string or getting a no from an API, then to avoid error don't use '_' numeric separator.
Similar goes for parseInt i.e anything after _ is discarded as shown below:
parseInt('25_00'); // 25

BigInt

Special type of integers, introduced in ES2020
Numbers are represented internally as 64 bits i.e 64 1s or 0s to represent any number. Only 53 are used to store the digits, remaining are used to store the position of decimal point and the sign. Hence, there is a limit on the size of the number i.e ((2*53) - 1). This is the biggest no which JS can safely represent. The base is 2, because we are working in binary form while storing.
2
*53 - 1; // 9007199254740991
Number.MAX_SAFE_INTEGER; // 9007199254740991

Anything larger than this is not safe i.e it cannot be represented accurately. Precision will be lost for numbers larger than this as shown in last digit. Sometimes it might work, whereas sometimes it won't.
Number.MAX_SAFE_INTEGER + 1; // 9007199254740992
Number.MAX_SAFE_INTEGER + 2; // 9007199254740992
Number.MAX_SAFE_INTEGER + 3; // 9007199254740994
Number.MAX_SAFE_INTEGER + 4; // 9007199254740996

Incase we get a larger no from an API larger than this, then JS won't be able to deal with it. So to resolve the above issue, BigInt a new primitive data type was introduces in ES2020. This can store integers as large as we want.

BigInt にするために、no の末尾に「n」が追加されます。例
const num = 283891738917391283734234324223122313243249821n;
数字; // 283891738917391283734234324223122313243249821n

BigInt は、このような巨大な数値を表示するための JS 方法です。
BigInt 数値を作成するために Constructor Fn を使用する別の方法。
const x = BigInt(283891738917391283734234324223122313243249821);
×; // 283891738917391288062871194223849945790676992n

演算: すべての算術演算子は BigInt と同じように機能します。
const x = 100n + 100n;
×; // 200n

const x = 10n * 10n;
×; // 100n

BigInt 数値と通常の数値を混在させないでください

const x = 100n;
const y = 10;
z = x*y; // エラー

これを機能させるには、BigInt コンストラクター Fn を使用します。
z = x * BigInt(y);
z; // 1000n

例外は、比較演算子と単項 + 演算子です。

20分> 19; // true
20n === 20; // false、=== は、JS が型強制を行うのを防ぎます。 LHS と RHS の両方に異なるプリミティブ型があるため、結果は「false」になります。

20n 型; // 'bigint'
タイプ20; // '数値'

20n == 20; // true、JS は BigInt を通常の数値に変換することで、型ではなく値のみを比較する型強制を実行します。
これも同様です: 20n == '20'; // true

例外:

+ 演算子を使用すると BigInt 数値が文字列に変換されません。
const num = 248923874328974239473829n
"num は巨大です。つまり " + num; // 'num は巨大です、つまり 248923874328974239473829'

注:
Math.sqrt は BigInt では動作しません。
BigInt の除算では、小数部分が切り捨てられます。
10/3; // 3.3333333333333335
10n / 3n; // 3n
12n / 3n; // 4n

この新しいプリミティブ型は、JS 言語にいくつかの新しい機能を追加し、巨大な言語でも機能するようにします。

The above is the detailed content of Math Namespace & BigInt. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!