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!
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).
let number1 = 10; // Integer
let number2 = 10.5; // Floating-point numberJavaScript 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.The toString() method converts a number to a string.
let number = 123;
let stringNumber = number.toString(); // "123"These methods help you format numbers with specific precision.
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)These methods convert a string to a number.
let string = "123";
let number1 = Number(string); // 123 (integer)
let number2 = parseFloat(string); // 123 (floating-point number)The isNaN() function checks if a value is Not a Number.
let number = 123;
let nonNumber = "abc";
console.log(isNaN(number)); // false
console.log(isNaN(nonNumber)); // trueThe Math object contains various mathematical constants and functions.
console.log(Math.PI); // 3.141592653589793 (pi)
console.log(Math.sqrt(16)); // 4 (square root of 16)What does the `toString()` method do in JavaScript?
What does the `isNaN()` function do in JavaScript?