Advertisement

Google Ad Slot: content-top

JS Number Method


Method

Description

Example

Number()

Convert string to a number

let str = "5";
Number(str) // 5

parseInt()

Convert string to a number

let str = "5";
parseInt(str) // 5
let str2 = "20px";
parseInt(str2) // 20

parseFloat()

Convert string to a float number

let str = "123.45";
parseFloat(str) // 123.45

toFixed()

Rounds to fixed decimals

let str = 3.14159;
str.toFixed(2) // "3.14"

toPrecision()

Rounds to significant digits

let str = 3.14159;
str.toPrecision(3) // "3.14"

isNaN()

Checks if value is NaN

let str = "hello";
isNaN(str) // true

isFinite()

Checks if a number is finite

let str = 42;
isFinite(str) // true
let str2 = 1/0;
isFinite(str2) // false

Math Object

JavaScript has a built-in Math object for advanced operations:

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 number
  • parseInt() / 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)
Try it yourself

Rounds to decimals:

  • toFixed() → Round for fixed decimals
  • precision() → Round for significant digits
Example
3.14159.toFixed(2) // "3.14"
3.14159.toPrecision(3) // "3.14"
Try it yourself

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
Try it yourself

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
Try it yourself