JavaScript is one of the most widely used programming languages in the world of web development and offers a range of methods for working with numbers. In this article, we will explore some common number methods in JavaScript and provide examples of how to use them.
1. toExponential()
This method returns the decimal form of a number in scientific notation.
let x = 123456;
console.log(x.toExponential(2)); // Output: 1.23e+5
2. toFixed()
This method returns a number with a fixed number of digits after the decimal point.
let x = 9.656;
console.log(x.toFixed(2)); // Output: 9.66
3. toPrecision()
This method returns a string representation of a number with a specified precision.
let x = 9.656;
console.log(x.toPrecision(2)); // Output: 9.7
4. toString()
This method converts a number to a string in a specified base (e.g., decimal, hexadecimal, or octal).
let x = 123;
console.log(x.toString()); // Output: "123"
console.log(x.toString(16)); // Output: "7b" (hexadecimal)
5. parseFloat()
This method converts a string into a floating-point number.
let x = parseFloat("10.00");
console.log(x); // Output: 10
6. parseInt()
This method converts a string into an integer.
let x = parseInt("10.00");
console.log(x); // Output: 10
These JavaScript number methods make working with numbers easier and allow for efficient number processing. These are just a few examples; JavaScript offers many more number methods to explore.