Advertisement
Google Ad Slot: content-top
JS Number Method
Method |
Description |
Example |
|---|---|---|
Convert string to a number |
let str = "5"; Number(str) // 5 |
|
Convert string to a number |
let str = "5"; parseInt(str) // 5 let str2 = "20px"; parseInt(str2) // 20 |
|
Convert string to a float number |
let str = "123.45"; parseFloat(str) // 123.45 |
|
Rounds to fixed decimals |
let str = 3.14159; str.toFixed(2) // "3.14" |
|
Rounds to significant digits |
let str = 3.14159; str.toPrecision(3) // "3.14" |
|
Checks if value is NaN |
let str = "hello"; isNaN(str) // true |
|
Checks if a number is finite |
let str = 42; isFinite(str) // true let str2 = 1/0; isFinite(str2) // false |
|
JavaScript has a built-in |
console.log(Math.PI); // 3.14159 console.log(Math.round(4.7)); // 5 console.log(Math.floor(4.7)); // 4 console.log(Math.ceil(4.7)); // 5 console.log(Math.random()); // Random number between 0 and 1 like 0.123587 |
Number Conversion
Number()→ Convert string to a numberparseInt()/parseFloat()
Example
let strNum = "123";
let num = Number(strNum); // 123
let intNum = parseInt(strNum); // 123
let floatNum = parseFloat("123.45"); // 123.45
console.log("5" - 2); // 3 (String "5" converted to number)
console.log("5" + 2); // "52" (2 converted to string)
Rounds to decimals:
toFixed()→ Round for fixed decimalsprecision()→ Round for significant digits
Checking if a Value is a Number:
isNaN() | Number.isInteger() | Number.isFinite()→ check if given value is number or not
Example
console.log(isNaN("Hello")); // true
console.log(Number.isInteger(42)); // true
console.log(Number.isFinite(42)); // true
Math Object for Numbers:
JavaScript has a built-in Math object for advanced operations:
Example
console.log(Math.PI); // 3.14159
console.log(Math.round(4.7)); // 5
console.log(Math.floor(4.7)); // 4
console.log(Math.ceil(4.7)); // 5
console.log(Math.random()); // Random number between 0 and 1