In TypeScript, number is a primitive type that can hold all kinds of numbers including integers, floats, hexadecimal, binary, octal, and scientific notation.
let age: number = 25;
let price: number = 99.99;
Usage in TypeScript with type annotation:
let score: number = 90;
let height: number = 5.9;
let hex: number = 0xff;
Useful Number Methods:
toFixed()
Rounds the number to a fixed number of decimal places:
let pi = 3.14159;
console.log(pi.toFixed(2)); // "3.14"
toExponential():
Converts to scientific notation:
let big = 123456;
console.log(big.toExponential()); // "1.23456e+5"
toString(radix):
Converts number to string in specified base:
let num = 255;
console.log(num.toString(16)); // "ff"
console.log(num.toString(2)); // "11111111"
Type Guarding:
Ensure type safety when using number | string:
function double(x: number | string) {
if (typeof x === "number") {
return x * 2;
}
return parseFloat(x) * 2;
}
Special Numeric Values:
let a = 1 / 0; // Infinity
let b = -1 / 0; // -Infinity
let c = parseInt("abc"); // NaN (Not a Number)
You should always check for isNaN() when doing conversions.
Math Library Functions:
Math.round(3.6); // 4
Math.floor(3.9); // 3
Math.ceil(3.1); // 4
Math.abs(-10); // 10
Math.pow(2, 3); // 8
Math.sqrt(16); // 4
Math.random(); // Random number between 0 and 1
Using Enums with Numbers:
enum Size {
Small = 1,
Medium = 2,
Large = 3
}
let selected: Size = Size.Medium;
Enums are great when you need readable numeric identifiers.
Custom Type Guard:
function isNumber(val: unknown): val is number {
return typeof val === "number" && !isNaN(val);
}
Number() constructor বা wrapper:
In JavaScript/TypeScript, the Number() function is used to convert other types (like strings or booleans) to a number. It can also be used as a wrapper object, though this is less common and generally discouraged.
let n = new Number(5); // object wrapper (not primitive)
typeof n; // "object"
isNaN() vs Number.isNaN()
New developers often don't know the difference between the global isNaN() function and Number.isNaN(). It would be good to mention this.
isNaN("abc"):; // true (coerces to NaN)
Number.isNaN("abc"); // false (doesn't coerce)
Number parsing functions:
Mentioning the Number() function alongside parseInt() and parseFloat() increases completeness.
Number("123.45"); // 123.45
Type narrowing with isFinite():
When dealing with scientific or dynamic values, isFinite() becomes helpful.
Number.isFinite(Infinity); // false
Top comments (1)
Thanks for clearing the concept, I was a little confused...