JavaScript uses numbers to represent both integers and floating-point values. Unlike some languages, JavaScript does not have different data types for integers and decimals—everything is treated as a floating-point number (64-bit IEEE 754 format).
Numbers can be created in JavaScript in multiple ways:
let x = 10; // Integer
let y = 10.5; // Floating-point number
let z = -25; // Negative number
Number()
Constructorlet a = Number(20);
let b = Number("50"); // Converts string to number
console.log(a, b); // 20, 50
If a number exceeds the maximum limit in JavaScript, it returns Infinity.
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
JavaScript returns NaN if a mathematical operation fails.
console.log("hello" * 5); // NaN
console.log(Number("abc")); // NaN
💡 isNaN(value)
checks if a value is NaN.
console.log(isNaN("hello")); // true
console.log(isNaN(123)); // false
parseInt()
– Converts to Integerconsole.log(parseInt("100px")); // 100
console.log(parseInt("50.99")); // 50
parseFloat()
– Converts to Floatconsole.log(parseFloat("50.99px")); // 50.99
Number()
– Converts Any Type to a Numberconsole.log(Number("20")); // 20
console.log(Number("20.5")); // 20.5
console.log(Number("Hello")); // NaN
JavaScript provides Math properties for working with numbers.
Property | Description |
---|---|
Math.PI |
Returns 3.14159… |
Math.E |
Euler’s number (2.718) |
Math.SQRT2 |
Square root of 2 |
Math.LN10 |
Natural logarithm of 10 |
Example:
console.log(Math.PI); // 3.141592653589793
console.log(Math.SQRT2); // 1.4142135623730951
console.log(Math.round(4.7)); // 5
console.log(Math.round(4.3)); // 4
console.log(Math.random()); // Example: 0.678234
💡 Generating a random integer between a range:
let min = 1, max = 10;
console.log(Math.floor(Math.random() * (max - min + 1)) + min);
JavaScript numbers are flexible and support various operations, including conversions, rounding, and random number generation. They play a crucial role in mathematical calculations and web development.
@asadmukhtar