Working with Numbers
In modern JavaScript, there are two primary types of numbers:
-
Regular numbers: These are stored in 64-bit format IEEE-754, commonly known as "double precision floating point numbers".
-
BigInt numbers: These represent integers of arbitrary length. They are necessary in situations where regular integer numbers exceed the maximum safe value or fall below the minimum safe value.
π₯ More ways to write a number
π₯ toString(base)
π₯ Rounding
π₯ Tests: isFinite and isNaN
π₯ Other math functions
Here are some alternative ways to represent numbers in JavaScript:
-
Using underscores as separators:
For example:
let billion = 1_000_000_000;
Underscores enhance readability by separating digits, but JavaScript ignores them, making
1_000_000_000
equivalent to1000000000
-
Using exponential notation with the letter "e":
For example:
let billion = 1e9; // 1 billion, equivalent to 1 and 9 zeroes alert(7.3e9); // 7.3 billion, same as 7300000000 or 7_300_000_000
In the above example,
e
notation multiplies the number by 1 with the specified number of zeroes. For instance,1e3
equals1 * 1000
, and1.23e6
equals1.23 * 1000000
-
Representing very small numbers:
For example:
let microsecond = 0.000001; let microsecond = 1e-6; // five zeroes to the left from 1
In the above example, negative number after "e" means division by 1 with the specified number of zeroes. For instance,
1e-3
equals1 / 1000
, and1.23e-6
equals1.23 / 1000000
.
Hex, binary and octal numbers
Hexadecimal numbers are represented using the prefix 0x
, binary numbers with 0b
, and octal numbers with 0o
. For example:
For example:
alert(0xff); // 255
alert(0b11111111); // 255 (binary)
alert(0o377); // 255 (octal)
These prefixes provide shorter and more convenient ways to represent numbers in their respective numeral systems.
The method num.toString(base)
converts the number num
into a string representation using the specified numeral system base.
For example:
let num = 255;
alert(num.toString(16)); // ff
alert(num.toString(2)); // 11111111
Common use-cases:
- Base 16 (hexadecimal) for colors and character encodings
- Base 2 (binary) for debugging bitwise operations
- Base 36 for representing long identifiers as shorter strings, such as in creating short URLs
Number rounding refers to the process of adjusting a numerical value to a specified precision or number of decimal places.
Math.floor()
rounds positive numbers towards zero and negative numbers towards negative infinity, effectively removing any decimal part
For example:
let num = 3.7;
let roundedDown = Math.floor(num); // 3
Math.ceil()
rounds up positive numbers to the nearest integer, moving towards positive infinity, and truncates negative numbers towards zero, removing anything after the decimal point
For example:
let num = 3.1;
let roundedUp = Math.ceil(num); // 4
- Math.round(): This function rounds a number to the nearest integer. It rounds to the nearest whole number, with halves rounded upwards
For example:
let num = 3.6;
let rounded = Math.round(num); // 4
Math.trunc()
removes the decimal part without rounding, differing fromMath.floor()
by truncating toward zero, including with negative numbers
For example:
let num = -3.9;
let truncated = Math.trunc(num); // -3
toFixed()
This method rounds a number to a specified number of digits after the decimal point and returns a string representation of the result
For example:
let num = 12.345;
let roundedStr = num.toFixed(2); // "12.35"
- Multiplication and Division: To round a number to n decimal places, multiply by 10^n, round, then divide by 10^n
JavaScript uses IEEE-754 double-precision floating-point format for numbers, which is binary. Though efficient, it faces limitations with certain decimal fractions.
Because of the binary nature of the format, decimal fractions that are simple in base-10 arithmetic can have repeating representations in binary. For instance, 0.1 in base-10 repeats in binary.
0.1 (base 10) = 0.0001100110011001100110011001100110011001100110011... (base 2)
This happens because the result of the addition, 0.30000000000000004, is the closest floating-point representation of the sum of 0.1 and 0.2 in the IEEE-754 format.
JavaScript offers methods like toFixed()
, toPrecision()
, and toExponential()
to format numbers with specific decimal places or significant digits. External libraries like decimal.js enable precise decimal arithmetic in JavaScript.
JavaScript provides two functions to check special numeric values: isNaN and isFinite.
isNaN(value)
checks if the value is NaN.
The isNaN function in JavaScript converts its argument to a number and then checks if it's NaN.
For example:
alert( isNaN(NaN) ); // true
alert( isNaN("str") ); // true
However, comparing NaN directly using === doesn't work as expected because NaN doesn't equal itself
alert( NaN === NaN ); // false
isFinite(value)
checks if the value is a regular number, excluding NaN, Infinity, and -Infinity.
The isFinite(value) function converts its argument to a number and returns true if itβs a regular number, excluding NaN, Infinity, and -Infinity:
- isFinite("15") returns true.
- isFinite("str") returns false because it's NaN
- isFinite(Infinity) returns false because it's Infinity
It's commonly used to validate whether a string value is a regular number
For example:
let num = +prompt("Enter a number", '');
// Returns true unless you enter Infinity, -Infinity, or not a number
alert( isFinite(num) );
parseInt()
and parseFloat()
are used to convert strings to numbers, especially when dealing with values containing units or currency symbols.
They handle parsing of numeric values with additional characters and units, such as "100px" or "19β¬".
parseInt()
and parseFloat()
extract a number from a string until they encounter a non-numeric character. If an error occurs, the function returns the parsed number.
parseInt()
returns an integer, while parseFloat()
returns a floating-point number.
For example:
alert( parseInt('10px') ); // 100
alert( parseFloat('12.5mm') ); // 12.5
alert( parseInt('98.9') ); // 12, only the integer part is returned
alert( parseFloat('67.5.4') ); // 12.3, the second point stops the reading
parseInt()
or parseFloat()
return NaN
if no digits are found in the input string before encountering a non-numeric character. For example:
alert(parseInt('a123')); // NaN
In the above example, NaN
is returned because the first character 'a'
is not a digit.
JavaScript includes a Math object, which provides various mathematical functions and constants.
Examples include:
Math.random()
: Returns a random number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // Example output: 0.8282435896381402
console.log(Math.random()); // Example output: 0.4618425245994924
Math.max(a, b, c...)
andMath.min(a, b, c...)
: Returns the largest and smallest values among the provided arguments.
console.log(Math.max(9, 58, -156, 190, 9)); // Example output: 190
console.log(Math.min(9, 58, -156, 190, 9)); // Example output: -156
Math.pow(n, power)
: Returns the result of raisingn
to the power ofpower
.
console.log(Math.pow(7, 4)); // Example output: 2401