JS Number Methods 🎯

beginner
14 min

JS Number Methods 🎯

Welcome to our comprehensive guide on JavaScript Number Methods! In this lesson, we'll explore various built-in methods for working with numbers in JavaScript. Let's dive in!

Understanding JavaScript Numbers 📝

Before we delve into the methods, let's quickly recap JavaScript numbers. In JavaScript, numbers are represented as either integers or floating-point numbers (with decimal points).

javascript
let number1 = 10; // Integer let number2 = 10.5; // Floating-point number

Number Methods Overview 💡

JavaScript provides several methods to manipulate numbers. Here's a brief overview:

  • toString(): Converts a number to a string.
  • toFixed(): Rounds a number to a specified number of decimal places and returns a string.
  • toPrecision(): Rounds a number to a specified length and returns a string.
  • parseInt() and parseFloat(): Convert a string to a number.
  • isNaN(): Checks if a value is Not a Number.
  • Math object: Contains various mathematical constants and functions.

toString() Method 📝

The toString() method converts a number to a string.

javascript
let number = 123; let stringNumber = number.toString(); // "123"

toFixed() and toPrecision() Methods 💡

These methods help you format numbers with specific precision.

javascript
let number = 123.456789; let fixedNumber = number.toFixed(2); // "123.46" (rounded to 2 decimal places) let precisionNumber = number.toPrecision(4); // "123.46" (rounded to 4 significant digits)

parseInt() and parseFloat() Methods 💡

These methods convert a string to a number.

javascript
let string = "123"; let number1 = Number(string); // 123 (integer) let number2 = parseFloat(string); // 123 (floating-point number)

isNaN() Method 💡

The isNaN() function checks if a value is Not a Number.

javascript
let number = 123; let nonNumber = "abc"; console.log(isNaN(number)); // false console.log(isNaN(nonNumber)); // true

Math Object 💡

The Math object contains various mathematical constants and functions.

javascript
console.log(Math.PI); // 3.141592653589793 (pi) console.log(Math.sqrt(16)); // 4 (square root of 16)

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `toString()` method do in JavaScript?

Quick Quiz
Question 1 of 1

What does the `isNaN()` function do in JavaScript?