Js Numbers in JavaScript
? JavaScript Numbers
In JavaScript, numbers are a primitive data type used for both integers and floating-point values. Unlike some other languages, JavaScript uses a single number type: IEEE 754 double-precision floating point.
? Declaring Numbers
let a = 42; // Integerlet b = 3.14; // Floating pointlet c = 1e6; // Scientific notation: 1 × 10? = 1000000let d = 0xff; // Hexadecimal: 255? Type Checking
typeof 123; // "number"typeof NaN; // "number" (Yes, `NaN` is of type "number")?? Special Numeric Values
| Value | Description |
|---|---|
Infinity | Positive infinity (1 / 0) |
-Infinity | Negative infinity (-1 / 0) |
NaN | Not a Number (e.g. 0 / "abc") |
console.log(1 / 0); // Infinityconsole.log("a" * 2); // NaN? Number Conversion
Convert from strings or other types using:
Number("123"); // 123parseInt("123.45"); // 123parseFloat("123.45"); // 123.45+"123"; // 123? Useful Number Methods
| Method | Description |
|---|---|
toString() | Converts number to string |
toFixed(n) | Formats number with n decimals |
toExponential(n) | Scientific notation |
toPrecision(n) | Formats to specified length |
(123.456).toFixed(2); // "123.46"(123.456).toPrecision(4); // "123.5"? Number Object vs Primitive
let x = 123; // Primitivelet y = new Number(123); // Object (Not recommended)?? Avoid using new Number() — it creates an object, not a primitive, and can lead to unexpected results.
? Examples
let a = 10 + 20; // 30let b = 10 * 5; // 50let c = 100 / 4; // 25let d = 7 % 3; // 1 (remainder)Summary
JavaScript has one number type for all numbers.
Handles integers, floats, scientific, hex, etc.
Includes special values like
NaN,Infinity.Useful methods:
toFixed(),toPrecision(),parseInt(), etc.
Would you like a breakdown of number methods, properties, or when to use BigInt for large numbers?