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 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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.