Representations of numbers¶
number
is a primitive type representing numeric values, both integer and floating point, e.g.:
const iAmANumber = 7;
const anotherNumber = 17.12423412312;
console.log(typeof(iAmANumber)); // number
console.log(typeof(anotherNumber)); // number
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 that's 2^53 - 1.
NaN - not a number¶
There is a special value of number
in JavaScript. This is the value of NaN
, which is Not a Number . This value represents something that is not a number. Most often we can meet it when performing numeric operations, when one of the values is of the wrong type (e.g. it is a string instead of a number). In order to check if a value is equal to Nan
, we can use the functionisNan ()
, e.g .:
console.log(typeof(Number.NaN)); // number
Number.isNaN(3 / 'notANumberReally'); // true
Popular methods¶
The number
primitive, which is wrapped by [object] (../ objects.md)Number
, has a number of useful methods. Some of them are:
parseInt
- creates an integer from the input stringparseFloat
- creates a floating point number from the input stringtoFixed
- allows you to format a numeric value up to a specified decimal place given as an argument. Rounds up when necessary.toString
- converts a numeric value to a string
The following example shows the use of these methods:
Number.parseInt('4'); // 4
Number.parseInt('five'); // NaN
Number.parseFloat('17.12'); // 17.12
123.45678.toFixed(4); // 123.4568 - rounding up
Number(8).toString(); // "8"
BigInt¶
bigint
is another JS primitive representing numeric values. Contrary to number
, it only stores integers and its maximum value is greater than the maximum value ofnumber
. In order to mark a numerical value as bigint
, we should add the letter n
at the end, e.g .:
const iAmBigInt = 9007199254740992n;
console.log(typeof(iAmBigInt)); //bigint
const sumOfBigInts = 2n + 3n;
console.log(sumOfBigInts); // 5n
NOTE: The Math object contains a set of methods for math operations. These methods only work with
number
.NOTE: When performing mathematical operations, we should not mix the
number
andbigint
types.