JavaScript Number Methods

JavaScript Number methods are functions that can be performed on numbers. They can be used to convert numbers to different formats, check their properties, and perform other operations.

To use a Number method, simply prefix the method name with the Number object. For example, to call the isInteger() method, you would use the following syntax:

Number.isInteger(10); // returns true

Note that Number methods can only be called on the Number object, not on individual number variables. For example, the following code will result in an error:

const x = 10;
x.isInteger();
// TypeError: x.isInteger is not a function

Common JavaScript Number Methods

Here is a list of some of the most common JavaScript Number methods:

Number(): Converts a value to a number. If the value cannot be converted, NaN is returned.

ParseInt(): Parses a string and returns an integer number parsed from the string.

ParseFloat(): Parses a string and returns a floating-point number parsed from the string.

ToExponential(): Returns a string that represents the exponential notation of the given number.

ToFixed(): Returns a string that represents a number formatted using fixed-point notation.

ToPrecision(): Returns a string that represents a number formatted using a specified precision.

ToLocaleString(): Returns a string that represents the number formatted according to the locale specified by the locales parameter.

IsInteger(): Returns true if the number is an integer, false otherwise.

IsFinite(): Returns true if the number is a finite number, false otherwise.

IsNaN(): Returns true if the number is NaNfalse otherwise.

Examples

Here are some examples of how to use JavaScript Number methods:

// Convert a string to a number
const str = "10";
const num = Number(str);
console.log(num);
// 10
// Parse a string as an integer
const str = "10.5";
const int = parseInt(str);
console.log(int);
// 10
// Parse a string as a floating-point number
const str = "10.5";
const float = parseFloat(str);
console.log(float);
// 10.5
// Format a number using exponential notation
const num = 123456789.0123456;
const exp = num.toExponential(2);
console.log(exp);
// 1.23e+8
// Format a number using fixed-point notation
const num = 123456789.0123456;
const fixed = num.toFixed(2);
console.log(fixed);
// 123456789.01
// Format a number using a specified precision
const num = 123456789.0123456;
const precision = num.toPrecision(8);
console.log(precision);
// 1.2345679e+8
// Format a number according to the locale specified by the `locales` parameter
const num = 123456789.0123456;
const locale = "en-US";
const localeString = num.toLocaleString(locale);
console.log(localeString);
// 123,456,789.01

Conclusion

JavaScript Number methods are a powerful tool for working with numbers. By learning how to use these methods, you can perform a variety of operations on numbers, such as converting them to different formats, checking their properties, and formatting them for display.