Introduction
In this article, we will cover Number Methods in JavaScript. Before we start, Let's understand the objective of this demonstration, which tells what exactly will be covered in this article.
- toFixed()
- toPrecision()
- parseInt()
- parseFloat()
- isFinite()
- toExponential()
So, Let's get started.
What is Number Methods?
A Number Method in JavaScript is a special action or function that you can use with numbers. These methods allow you to do things like rounding numbers, converting numbers to a specific format, and performing mathematical operations on numbers. They are like tools that help you work with numbers more effectively in your JavaScript code.
toFixed() method in JavaScript
This method is used to round a number to a specified number of decimal places and returns a string.
let num = 5.24159;
let rounded = num.toFixed(2); // "5.24"
toPrecision() method in JavaScript
This method is used to format a number to a specified length and returns a string. It includes both the integer and decimal parts of the number.
let num = 123.456;
let formatted = num.toPrecision(4); // "123.5"
parseInt() method in JavaScript
This function parses a string and returns an integer. It stops parsing when it encounters a non-numeric character.
let str = "123";
let parsedInt = parseInt(str); // 123
parseFloat() method in JavaScript
This function parses a string and returns a floating-point number.
let str = "3.14";
let parsedFloat = parseFloat(str); // 3.14
isFinite() method in JavaScript
This function checks if a value is a finite number (not Infinity or -Infinity). It returns true if the value is finite, and false otherwise.
isFinite(42); // true
isFinite(Infinity); // false
toExponential() method in JavaScript
This method converts a number to exponential notation and returns a string.
let num = 1000;
let exponential = num.toExponential(); // "1e+3"
Summary
In this article, I have tried to cover Number Method in Javascript.