The Number data type is used to represent numeric values, e.g. integer, floating-point, and exponential numbers, and is essential for mathematical calculations and storing values.
let x = 10 // positive integer let y = -20 // negative integer let z = 0 // zero
Standard operations are straightforward:
let sum = 10 + 5 // 15 let multiply = 10 * 5 // 50 let divide = 10 / 5 // 2 let subtract = 10 - 5 // 5
Floating-Point (decimal) Numbers
-1.7976931348623157 x 10^308 and
1.7976931348623157 x 10^308. Due to the way that floating-point numbers are represented in memory, they can sometimes lead to precision errors, which can be problematic in some calculations.
let x = 3.14 // positive floating-point number let y = -0.5 // negative floating-point number let z = 0.0 // floating-point zero
Operations work just as expected (or, do they?!):
let sum = 0.1 + 0.2 // 0.30000000000000004
In the above example, the value of
sum is not precisely
0.3, but it is
0.30000000000000004. When working with financial data or other types of applications that require high precision, the
toFixed() method can be used to round the value to a specified number of decimal places.
let pi = 3.14159; console.log(pi.toFixed(2)); // 3.14
The Floating-Point data type is useful in scientific calculations and calculations that require high precision.
Exponential numbers are written using the letter "e" and are used to represent very large or very small numbers - the letter "e" represents "10 raised to the power of" the number that follows:
let x = 5e3 // 5000 (5 times 10 raised to the power of 3) let y = 5e-3 // 0.005 (5 times 10 raised to the power of -3)
Here are some exponential numbers used to represent very large or very small numbers (ideal for scientific calculations):
let distanceToSun = 149.6e6 // distance to the sun in kilometers let hairWidth = 0.003e-3 // width of a human hair in meters
Type Checks and Conversion
isNaN(), which is used to check if a value is not a number, and
parseInt(), which parses a string and returns an integer.
let notANum = "hello"; console.log(isNaN(notANum)); // true let stringNum = "10"; let num = parseInt(stringNum); console.log(num); // 10