JavaScript provides a variety of methods that can be used with numbers to perform operations, manipulate data, and format output. Here are some commonly used number methods in JavaScript:
toFixed()
The toFixed()
method rounds a number to a specified number of decimal places and returns a string. The argument passed to toFixed()
is the number of decimal places to round to:
let num = 3.14159;
console.log(num.toFixed(2)); // Outputs: "3.14"
toPrecision()
The toPrecision()
method rounds a number to a specified number of significant digits and returns a string. The argument passed to toPrecision()
is the number of significant digits to round to:
let num = 123.456;
console.log(num.toPrecision(4)); // Outputs: "123.5"
toString()
The toString()
method converts a number to a string:
let num = 42;
console.log(num.toString()); // Outputs: "42"
The toString()
method can also take an optional argument that specifies the base to use when converting the number to a string. The default base is 10, but other bases can be used, such as 2 for binary or 16 for hexadecimal:
let num = 42;
console.log(num.toString(2)); // Outputs: "101010"
console.log(num.toString(16)); // Outputs: "2a"
isNaN()
The isNaN()
method determines whether a value is NaN
(not a number):
console.log(isNaN("hello")); // Outputs: true
console.log(isNaN(42)); // Outputs: false
isFinite()
The isFinite()
method determines whether a value is a finite number:
console.log(isFinite(42)); // Outputs: true
console.log(isFinite(Infinity)); // Outputs: false
parseInt()
The parseInt()
method converts a string to an integer. It takes an optional second argument that specifies the base to use when converting the string:
let numStr = "42";
console.log(parseInt(numStr)); // Outputs: 42
let hexStr = "2a";
console.log(parseInt(hexStr, 16)); // Outputs: 42
parseFloat()
The parseFloat()
method converts a string to a floating-point number:
let numStr = "3.14";
console.log(parseFloat(numStr)); // Outputs: 3.14
Understanding how to use number methods in JavaScript is essential for performing various operations, manipulating data, and formatting output. By using methods like toFixed()
, toPrecision()
, toString()
, isNaN()
, isFinite()
, parseInt()
, and parseFloat()
, you can create more powerful and flexible applications that perform complex calculations and data manipulation.