JS Basic Tutorial
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()
→ Convert string to a numberparseInt()
/ parseFloat()
Try it yourself
toFixed()
→ Round for fixed decimalsprecision()
→ Round for significant digitsisNaN() | Number.isInteger() | Number.isFinite()
→ check if given value is number or notTry it yourself
JavaScript has a built-in Math
object for advanced operations:
Try it yourself