Please support this book: buy it or donate

15. Numbers



This chapter covers JavaScript’s single type for numbers, number.

15.1. JavaScript only has floating point numbers

You can express both integers and floating point numbers in JavaScript:

  1. 98
  2. 123.45

However, there is only a single type for all numbers: They are all doubles, 64-bit floating point numbers implemented according to the IEEE Standard for Floating-Point Arithmetic (IEEE 754).

Integers are simply floating point numbers without a decimal fraction:

  1. > 98 === 98.0
  2. true

Note that, under the hood, most JavaScript engines are often able to use real integers, with all associated performance and storage size benefits.

15.2. Number literals

Let’s examine literals for numbers.

15.2.1. Integer literals

Several integer literals let you express integers with various bases:

  1. // Binary (base 2)
  2. assert.equal(0b11, 3);
  3. // Octal (base 8)
  4. assert.equal(0o10, 8);
  5. // Decimal (base 10):
  6. assert.equal(35, 35);
  7. // Hexadecimal (base 16)
  8. assert.equal(0xE7, 231);

15.2.2. Floating point literals

Floating point numbers can only be expressed in base 10.

Fractions:

  1. > 35.0
  2. 35

Exponent: eN means ×10N

  1. > 3e2
  2. 300
  3. > 3e-2
  4. 0.03
  5. > 0.3e2
  6. 30

15.2.3. Syntactic pitfall: properties of integer literals

Accessing a property of an integer literal entails a pitfall: If the integer literal is immediately followed by a dot then that dot is interpreted as a decimal dot:

  1. 7.toString(); // syntax error

There are four ways to work around this pitfall:

  1. 7.0.toString()
  2. (7).toString()
  3. 7..toString()
  4. 7 .toString() // space before dot

15.3. Number operators

15.3.1. Binary arithmetic operators

  1. assert.equal(1 + 4, 5); // addition
  2. assert.equal(6 - 3, 3); // subtraction
  3. assert.equal(2 * 1.25, 2.5); // multiplication
  4. assert.equal(6 / 4, 1.5); // division
  5. assert.equal(6 % 4, 2); // remainder
  6. assert.equal(2 ** 3, 8); // exponentiation

% is a remainder operator (not a modulo operator) – its result has the sign of the first operand:

  1. > 3 % 2
  2. 1
  3. > -3 % 2
  4. -1

15.3.2. Unary plus and negation

  1. assert.equal(+(-3), -3); // unary plus
  2. assert.equal(-(-3), 3); // unary negation

Both operators coerce their operands to numbers:

  1. > +'7'
  2. 7
  3. > +'-12'
  4. -12
  5. > -'9'
  6. -9

15.3.3. Incrementing (++) and decrementing (—)

The incrementation operator ++ exists in a prefix version and a suffix version. In both versions, it destructively adds one to its operand. Therefore, its operand must be a storage location that can be changed. The decrementation operator works the same, but subtracts one from its operand. The next two examples explain the difference between the prefix and the suffix version.

Prefix ++ and prefix : change and then return.

  1. let foo = 3;
  2. assert.equal(++foo, 4);
  3. assert.equal(foo, 4);
  4. let bar = 3;
  5. assert.equal(--bar, 2);
  6. assert.equal(bar, 2);

Suffix ++ and suffix : return and then change.

  1. let foo = 3;
  2. assert.equal(foo++, 3);
  3. assert.equal(foo, 4);
  4. let bar = 3;
  5. assert.equal(bar--, 3);
  6. assert.equal(bar, 2);
15.3.3.1. Operands: not just variables

You can also apply these operators to property values:

  1. const obj = { a: 1 };
  2. ++obj.a;
  3. assert.equal(obj.a, 2);

And to Array elements:

  1. const arr = [ 4 ];
  2. arr[0]++;
  3. assert.deepEqual(arr, [5]);

15.4. Converting to number

These are three ways of converting values to numbers:

  • Number(value)
  • +value
  • parseFloat(value) (avoid; different than the other two!)
    Recommendation: use the descriptive Number().

Examples:

  1. assert.equal(Number(undefined), NaN);
  2. assert.equal(Number(null), 0);
  3. assert.equal(Number(false), 0);
  4. assert.equal(Number(true), 1);
  5. assert.equal(Number(123), 123);
  6. assert.equal(Number(''), 0);
  7. assert.equal(Number('123'), 123);
  8. assert.equal(Number('xyz'), NaN);

How objects are converted to numbers can be configured. For example, by overriding .valueOf():

  1. > Number({ valueOf() { return 123 } })
  2. 123

15.5. Error values

Two number values are returned when errors happen:

  • NaN
  • Infinity

15.6. Error value: NaN

NaN is an abbreviation of “not a number”. Ironically, JavaScript considers it to be a number:

  1. > typeof NaN
  2. 'number'

When is NaN returned?

NaN is returned if a number can’t be parsed:

  1. > Number('$$$')
  2. NaN
  3. > Number(undefined)
  4. NaN

NaN is returned if an operation can’t be performed:

  1. > Math.log(-1)
  2. NaN
  3. > Math.sqrt(-1)
  4. NaN

NaN is returned if an operand or argument is NaN (to propagate errors):

  1. > NaN - 3
  2. NaN
  3. > 7 ** NaN
  4. NaN

15.6.1. Checking for NaN

NaN is the only JavaScript value that is not strictly equal to itself:

  1. const n = NaN;
  2. assert.equal(n === n, false);

These are several ways of checking if a value x is NaN:

  1. const x = NaN;
  2. assert.equal(Number.isNaN(x), true); // preferred
  3. assert.equal(Object.is(x, NaN), true);
  4. assert.equal(x !== x, true);

In the last line, we use the comparison quirk to detect NaN.

15.6.2. Finding NaN in Arrays

Some Array methods can’t find NaN:

  1. > [NaN].indexOf(NaN)
  2. -1

Others can:

  1. > [NaN].includes(NaN)
  2. true
  3. > [NaN].findIndex(x => Number.isNaN(x))
  4. 0
  5. > [NaN].find(x => Number.isNaN(x))
  6. NaN

Alas, there is no simple rule of thumb, you have to check for each method, how it handles NaN.

15.7. Error value: Infinity

When is the error value Infinity returned?

Infinity is returned if a number is too large:

  1. > Math.pow(2, 1023)
  2. 8.98846567431158e+307
  3. > Math.pow(2, 1024)
  4. Infinity

Infinity is returned if there is a division by zero:

  1. > 5 / 0
  2. Infinity
  3. > -5 / 0
  4. -Infinity

15.7.1. Infinity as a default value

Infinity is larger than all other numbers (except NaN), making it a good default value:

  1. function findMinimum(numbers) {
  2. let min = Infinity;
  3. for (const n of numbers) {
  4. if (n < min) min = n;
  5. }
  6. return min;
  7. }
  8. assert.equal(findMinimum([5, -1, 2]), -1);
  9. assert.equal(findMinimum([]), Infinity);

15.7.2. Checking for Infinity

These are two common ways of checking if a value x is Infinity:

  1. const x = Infinity;
  2. assert.equal(x === Infinity, true);
  3. assert.equal(Number.isFinite(x), false);

15.8. The precision of numbers: careful with decimal fractions

Internally, JavaScript floating point numbers are represented with base 2 (according to the IEEE 754 standard). That means that decimal fractions (base 10) can’t always be represented precisely:

  1. > 0.1 + 0.2
  2. 0.30000000000000004
  3. > 1.3 * 3
  4. 3.9000000000000004
  5. > 1.4 * 100000000000000
  6. 139999999999999.98

You therefore need to take rounding errors into consideration when performing arithmetic in JavaScript.

Read on for an explanation of this phenomenon.

15.9. (Advanced)

All remaining sections of this chapter are advanced.

15.10. Background: floating point precision

In JavaScript, computations with numbers don’t always produce precise results. For example:

  1. > 0.1 + 0.2
  2. 0.30000000000000004

To understand why, we need to explore how JavaScript represents floating point numbers internally. It uses three integers to do so, as described in tbl. 5.

Table 5: Internally, JavaScript uses three integers to represent floating point numbers. They take up a total of 64 bits of storage (double precision).
ComponentSizeInteger range
sign1 bit[0, 1]
fraction52 bits[0, 252−1]
exponent11 bits[−1023, 1024]

The floating point number represented by these integers is computed as follows:

(–1)sign × 0b1.fraction × 2exponent

To make further discussions easier, we simplify this representation:

  • Instead of base 2 (binary), we use base 10 (decimal), because that’s what most people are more familiar with.
  • The fraction is a natural number that is interpreted as a fraction (digits after a point). We switch to a mantissa, an integer that is interpreted as itself. As a consequence, the exponent is used differently, but its fundamental role doesn’t change.
  • As the mantissa is an integer (with its own sign), we don’t need a separate sign, anymore.
    The new representation works like this:
mantissa × 10exponent

Let’s try out this representation for a few floating point numbers.

  • For the integer −123, we mainly need the mantissa:
  1. > -123 * (10 ** 0)
  2. -123
  • For the number 1.5, we imagine there being a point after the mantissa. We use a negative exponent to move that point one digit to the left:
  1. > 15 * (10 ** -1)
  2. 1.5
  • For the number 0.25, we move the point two digits to the left:
  1. > 25 * (10 ** -2)
  2. 0.25

Representations with negative exponents can also be written as fractions with positive exponents in the denominators:

  1. > 15 * (10 ** -1) === 15 / 10
  2. true
  3. > 25 * (10 ** -2) === 25 / 100
  4. true

These fractions help with understanding why there are numbers that our encoding cannot represent:

  • 1/10 can be represented. It already has the required format: a power of 10 in the denominator.
  • 1/2 can be represented as 5/10. We turned the 2 in the denominator into a power of 10, by multiplying numerator and denominator with 5.
  • 1/4 can be represented as 25/100. We turned the 4 in the denominator into a power of 10, by multiplying numerator and denominator with 25.
  • 1/3 cannot be represented. There is no way to turn the denominator into a power of 10. (The prime factors of 10 are 2 and 5. Therefore, any denominator that only has these prime factors can be converted to a power of 10, by multiplying both numerator and denominator with enough twos and fives. If a denominator has a different prime factor, then there’s nothing we can do.)
    To conclude out excursion, we switch back to base 2:

  • 0.5 = 1/2 can be represented with base 2, because the denominator is already a power of 2.

  • 0.25 = 1/4 can be represented with base 2, because the denominator is already a power of 2.
  • 0.1 = 1/10 cannot be represented, because the denominator cannot be converted to a power of 2.
  • 0.2 = 2/10 cannot be represented, because the denominator cannot be converted to a power of 2.
    Now we can see why 0.1 + 0.2 doesn’t produce a precise result: Internally, neither of the two operands can be represented precisely.

The only way to compute precisely with decimal fractions is by internally switching to base 10. For many programming languages, base 2 is the default and base 10 an option. For example, Java has the class BigDecimal and Python has the module decimal. There are tentative plans to add something similar to JavaScript: The ECMAScript proposal “Decimal” is currently at stage 0.

15.11. Integers in JavaScript

JavaScript doesn’t have a special type for integers. Instead, they are simply normal (floating point) numbers without a decimal fraction:

  1. > 1 === 1.0
  2. true
  3. > Number.isInteger(1.0)
  4. true

In this section, we’ll look at a few tools for working with these pseudo-integers.

15.11.1. Converting to integer

The recommended way of converting numbers to integers is to use one of the rounding methods of the Math object (which is documented in the next chapter):

  • Math.floor(n): returns the largest integer in
  1. > Math.floor(2.1)
  2. 2
  3. > Math.floor(2.9)
  4. 2
  • Math.ceil(n): returns the smallest integer in
  1. > Math.ceil(2.1)
  2. 3
  3. > Math.ceil(2.9)
  4. 3
  • Math.round(n): returns the integer that is “closest” to n. 0.5 is rounded up. For example:
  1. > Math.round(2.4)
  2. 2
  3. > Math.round(2.5)
  4. 3
  • Math.trunc(n): removes any decimal fraction (after the point) that n has, therefore turning it into an integer.
  1. > Math.trunc(2.1)
  2. 2
  3. > Math.trunc(2.9)
  4. 2

Tbl. 6 shows the results of these functions for various inputs.

Table 6: Functions for converting numbers to integers. Note how things change with negative numbers, because “larger” always means “closer to positive infinity”.
-2.9-2.5-2.12.12.52.9
Math.floor-3-3-3222
Math.ceil-2-2-2333
Math.round-3-2-2233
Math.trunc-2-2-2222

15.11.2. Ranges of integers in JavaScript

These are important ranges of integers in JavaScript:

  • Safe integers: can be represented “safely” by JavaScript (more on what that means next)
    • Precision: 53 bits plus sign
    • Range: (−253, 253)
  • Array indices
    • Precision: 32 bits, unsigned
    • Range: [0, 232−1) (excluding the maximum length)
    • Typed Arrays have a larger range of 53 bits (safe and unsigned)
  • Bitwise operands (bitwise Or etc.)
    • Precision: 32 bits
    • Range of unsigned right shift (>>>): unsigned, [0, 232)
    • Range of all other bitwise operators: signed, [−231, 231)

15.11.3. Safe integers

This is the range of integers that are safe in JavaScript:

[–253–1, 253–1]

An integer is safe if it is represented by exactly one JavaScript number. Given that JavaScript numbers are encoded as a fraction multiplied by 2 to the power of an exponent, higher integers can also be represented, but then there are gaps between them.

For example (18014398509481984 is 254):

  1. > 18014398509481984
  2. 18014398509481984
  3. > 18014398509481985
  4. 18014398509481984
  5. > 18014398509481986
  6. 18014398509481984
  7. > 18014398509481987
  8. 18014398509481988

The following properties of Number help determine if an integer is safe:

  1. assert.equal(Number.MAX_SAFE_INTEGER, (2 ** 53) - 1);
  2. assert.equal(Number.MIN_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER);
  3. assert.equal(Number.isSafeInteger(5), true);
  4. assert.equal(Number.isSafeInteger('5'), false);
  5. assert.equal(Number.isSafeInteger(5.1), false);
  6. assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER), true);
  7. assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER+1), false);
15.11.3.1. Safe computations

Let’s look at computations involving unsafe integers.

The following result is incorrect and unsafe, even though both of its operands are safe.

  1. > 9007199254740990 + 3
  2. 9007199254740992

The following result is safe, but incorrect. The first operand is unsafe, the second operand is safe.

  1. > 9007199254740995 - 10
  2. 9007199254740986

Therefore, the result of an expression a op b is correct if and only if both operands and the result are safe:

  1. isSafeInteger(a) && isSafeInteger(b) && isSafeInteger(a op b)

15.12. Bitwise operators

JavaScript’s bitwise operators work as follows:

  • First, the operands are converted to numbers (64-bit double floating point numbers), then to 32-bit integers.
  • Then the bitwise operation is performed.
  • Last, the result is converted back to a double and returned.
    Internally, the operators use the following integer ranges (input and output):

  • Unsigned right shift operator (>>>): 32 bits, range [0, 232)

  • All other bitwise operators: 32 bits including a sign, range [−231, 231)
    The results of some of these operators are easiest to understand if we display them as unsigned 32-bit integers, in binary notation. That’s what b32() does (whose implementation is shown later):
  1. assert.equal(
  2. b32(-1),
  3. '11111111111111111111111111111111');
  4. assert.equal(
  5. b32(1),
  6. '00000000000000000000000000000001');
  7. assert.equal(
  8. b32(2 ** 31),
  9. '10000000000000000000000000000000');

15.12.1. Binary bitwise operators

Table 7: Binary bitwise operators.
OperationName
num1 & num2Bitwise And
num1 | num2Bitwise Or
num1 ^ num2Bitwise Xor

The binary operators (tbl. 7) combine the bits of their operands to produce their results:

  1. > (0b1010 & 0b11).toString(2).padStart(4, '0')
  2. '0010'
  3. > (0b1010 | 0b11).toString(2).padStart(4, '0')
  4. '1011'
  5. > (0b1010 ^ 0b11).toString(2).padStart(4, '0')
  6. '1001'

15.12.2. Bitwise Not

Table 8: The bitwise Not operator.
OperationName
~numBitwise Not, ones’ complement

The bitwise Not operator (tbl. 8) inverts each binary digit of its operand:

  1. > b32(~0b100)
  2. '11111111111111111111111111111011'

15.12.3. Bitwise shift operators

Table 9: Bitwise shift operators.
OperationName
num << countLeft shift
num >> countSigned right shift
num >>> countUnsigned right shift

The shift operators (tbl. 9) move binary digits to the left or to the right:

  1. > (0b10 << 1).toString(2)
  2. '100'

>> preserves highest bit, >>> doesn’t:

  1. > b32(0b10000000000000000000000000000010 >> 1)
  2. '11000000000000000000000000000001'
  3. > b32(0b10000000000000000000000000000010 >>> 1)
  4. '01000000000000000000000000000001'

15.12.4. b32(): displaying 32-bit integers in binary notation

We have now used b32() a few times. The following code is an implementation of it.

  1. /**
  2. * Return a string representing n as a 32-bit unsigned integer,
  3. * in binary notation.
  4. */
  5. function b32(n) {
  6. // >>> ensures highest bit isn’t interpreted as a sign
  7. return (n >>> 0).toString(2).padStart(32, '0');
  8. }
  9. assert.equal(
  10. b32(6),
  11. '00000000000000000000000000000110');

n >>> 0 means that we are shifting n zero bits to the right. Therefore, in principle, the >>> operator does nothing, but it still coerces n to an unsigned 32-bit integer:

  1. > 12 >>> 0
  2. 12
  3. > -12 >>> 0
  4. 4294967284
  5. > (2**32 + 1) >>> 0
  6. 1

15.13. Quick reference: numbers

15.13.1. Converting to number

Tbl. 10 shows what happens if you convert various values to numbers via Number().

Table 10: Converting values to numbers.
xNumber(x)
undefinedNaN
null0
booleanfalse 0, true 1
numberx (no change)
string'' 0
other parsed number, ignoring leading/trailing whitespace
objectconfigurable (e.g. via .valueOf())

15.13.2. Arithmetic operators

JavaScript has the following arithmetic operators:

  • Binary arithmetic operators (tbl. 11)
  • Prefix and suffix arithmetic operators (tbl. 12)
Table 11: Binary arithmetic operators.
OperatorNameExample
n + mAdditionES13 + 4 7
n - mSubtractionES19 - 1 8
n mMultiplicationES13 2.25 6.75
n / mDivisionES15.625 / 5 1.125
n % mRemainderES18 % 5 3
-8 % 5 -3
n mExponentiationES20164 2 16
Table 12: Prefix and suffix arithmetic operators
OperatorNameExample
+nUnary plusES1+(-7) -7
-nUnary negationES1-(-7) 7
v++IncrementES1let v=0; [v++, v] [0, 1]
++vIncrementES1let v=0; [++v, v] [1, 1]
v—DecrementES1let v=1; [v—, v] [1, 0]
—vDecrementES1let v=1; [—v, v] [0, 0]

15.13.3. Bitwise operators

JavaScript has the following bitwise operators:

  • Bitwise And, Or, Xor, Not (tbl. 13)
  • Bitwise shift operators (tbl. 14)
    Operands and results of bitwise operators:

  • Unsigned right shift operator (>>>): 32 bits, range [0, 232)

  • All other bitwise operators: 32 bits including a sign, range [−231, 231)
    The helper function b32() for displaying binary numbers is shown earlier in this chapter.
Table 13: Bitwise And, Or, Xor, Not.
OperatorNameExample
i & jBitwise AndES1(0b1010 & 0b1100).toString(2) '1000'
i | jBitwise OrES1(0b1010 | 0b1100).toString(2) '1110'
i ^ jBitwise XorES1(0b1010 ^ 0b0011).toString(2) '1001'
~iBitwise NotES1~0b11111111111111111111111111111110 1
Table 14: Bitwise shift operators.
OperatorNameExample
i << jLeft shiftES1(0b1 << 1).toString(2) '10'
i >> jSigned right shiftES1b32(0b10000000000000000000000000000010 >> 1)
'11000000000000000000000000000001'
i >>> jUnsigned right shiftES1b32(0b10000000000000000000000000000010 >>> 1)
'01000000000000000000000000000001'

15.13.4. Global functions for numbers

JavaScript has the following four global functions for numbers:

  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()
    However, it is better to use the corresponding methods of Number, which have fewer pitfalls: Number.isFinite(), Number.isNaN(), Number.parseFloat(), Number.parseInt(). They were introduced with ES6 and are discussed below.

15.13.5. Static properties of Number

  • .EPSILON: number [ES6]

The difference between 1 and the next representable floating point number. In general, a machine epsilon provides an upper bound for rounding errors in floating point arithmetic.

  • Approximately: 2.2204460492503130808472633361816 × 10-16
    • .MAX_SAFE_INTEGER: number [ES6]

The largest integer that JavaScript can represent unambiguously (253−1).

  • .MAX_VALUE: number [ES1]

The largest positive finite JavaScript number.

  • Approximately: 1.7976931348623157 × 10308
    • .MIN_SAFE_INTEGER: number [ES6]

The smallest integer that JavaScript can represent unambiguously (−253+1).

  • .MIN_VALUE: number [ES1]

The smallest positive JavaScript number. Approximately 5 × 10−324.

  • .NaN: number [ES1]

The same as the global variable NaN.

  • .NEGATIVE_INFINITY: number [ES1]

The same as -Number.POSITIVE_INFINITY.

  • .POSITIVE_INFINITY: number [ES1]

The same as the global variable Infinity.

15.13.6. Static methods of Number

  • .isFinite(num: number): boolean [ES6]

Returns true if num is an actual number (neither Infinity nor -Infinity nor NaN).

  1. > Number.isFinite(Infinity)
  2. false
  3. > Number.isFinite(-Infinity)
  4. false
  5. > Number.isFinite(NaN)
  6. false
  7. > Number.isFinite(123)
  8. true
  • .isInteger(num: number): boolean [ES6]

Returns true if num is a number and does not have a decimal fraction.

  1. > Number.isInteger(-17)
  2. true
  3. > Number.isInteger(33)
  4. true
  5. > Number.isInteger(33.1)
  6. false
  7. > Number.isInteger('33')
  8. false
  9. > Number.isInteger(NaN)
  10. false
  11. > Number.isInteger(Infinity)
  12. false
  • .isNaN(num: number): boolean [ES6]

Returns true if num is the value NaN:

  1. > Number.isNaN(NaN)
  2. true
  3. > Number.isNaN(123)
  4. false
  5. > Number.isNaN('abc')
  6. false
  • .isSafeInteger(num: number): boolean [ES6]

Returns true if num is a number and unambiguously represents an integer.

  • .parseFloat(str: string): number [ES6]

Coerces its parameter to string and parses it as a floating point number. For converting strings to numbers, Number() (which ignores leading and trailing whitespace) is usually a better choice than Number.parseFloat() (which ignores leading whitespace and illegal trailing characters and can hide problems).

  1. > Number.parseFloat(' 123.4#')
  2. 123.4
  3. > Number(' 123.4#')
  4. NaN
  • .parseInt(str: string, radix=10): number [ES6]

Coerces its parameter to string and parses it as an integer, ignoring leading whitespace and illegal trailing characters:

  1. > Number.parseInt(' 123#')
  2. 123

The parameter radix specifies the base of number to be parsed:

  1. > Number.parseInt('101', 2)
  2. 5
  3. > Number.parseInt('FF', 16)
  4. 255

Do not use this method to convert numbers to integers: Coercing to string is inefficient. And stopping before the first non-digit is not a good algorithm for removing the fraction of a number. Here is an example where it goes wrong:

  1. > Number.parseInt(1e21, 10) // wrong
  2. 1

It is better to use one of the rounding functions of Math to convert a number to an integer:

  1. > Math.trunc(1e21) // correct
  2. 1e+21

15.13.7. Methods of Number.prototype

  • .toExponential(fractionDigits?: number): string [ES3]

Returns a string that represents the number via exponential notation. With fractionDigits, you can specify, how many digits should be shown of the number that is multiplied with the exponent (the default is to show as many digits as necessary).

Example: number too small to get a positive exponent via .toString().

  1. > 1234..toString()
  2. '1234'
  3. > 1234..toExponential()
  4. '1.234e+3'
  5. > 1234..toExponential(5)
  6. '1.23400e+3'

Example: fraction not small enough to get a negative exponent via .toString().

  1. > 0.003.toString()
  2. '0.003'
  3. > 0.003.toExponential()
  4. '3e-3'
  5. > 0.003.toExponential(4)
  6. '3.0000e-3'
  • .toFixed(fractionDigits=0): string [ES3]

Returns an exponent-free representation of the number, rounded to fractionDigits digits.

  1. > 0.0000003.toString()
  2. '3e-7'
  3. > 0.0000003.toFixed(10)
  4. '0.0000003000'
  5. > 0.0000003.toFixed()
  6. '0'

If the number is 1021 or greater, even .toFixed() uses an exponent:

  1. > (10 ** 21).toFixed()
  2. '1e+21'
  • .toPrecision(precision?: number): string [ES3]

Works like .toString(), but prunes the mantissa to precision digits before returning a result. If precision is missing, .toString()is used.

  1. > 1234..toPrecision(3) // requires exponential notation
  2. '1.23e+3'
  3. > 1234..toPrecision(4)
  4. '1234'
  5. > 1234..toPrecision(5)
  6. '1234.0'
  7. > 1.234.toPrecision(3)
  8. '1.23'
  • .toString(radix=10): string [ES1]

Returns a string representation of the number.

Returning a result with base 10:

  1. > 123.456.toString()
  2. '123.456'

Returning results with bases other than 10 (specified via radix):

  1. > 4..toString(2)
  2. '100'
  3. > 4.5.toString(2)
  4. '100.1'
  5. > 255..toString(16)
  6. 'ff'
  7. > 255.66796875.toString(16)
  8. 'ff.ab'
  9. > 1234567890..toString(36)
  10. 'kf12oi'

You can use parseInt() to convert integer results back to numbers:

  1. > parseInt('kf12oi', 36)
  2. 1234567890

15.13.8. Sources