Js Number Methods in JavaScript
? JavaScript Number Methods
JavaScript provides several built-in methods to work with numbers. These methods are part of the Number object and help format, convert, and manipulate numeric values.
? Common Number Methods
| Method | Description | Example |
|---|---|---|
toString() | Converts number to a string | (123).toString(); // "123" |
toFixed(n) | Rounds number to n decimal places (as a string) | (3.14159).toFixed(2); // "3.14" |
toExponential(n) | Returns exponential notation (string) | (9.99e5).toExponential(2); |
toPrecision(n) | Formats to n digits total | (123.456).toPrecision(4); // "123.5" |
valueOf() | Returns the primitive value of a Number object | (123).valueOf(); // 123 |
Number.isFinite(x) | Checks if x is a finite number | Number.isFinite(10); // true |
Number.isInteger(x) | Checks if x is an integer | Number.isInteger(10.5); // false |
Number.parseInt(str) | Parses a string and returns an integer | Number.parseInt("42.9"); // 42 |
Number.parseFloat(str) | Parses a string and returns a float | Number.parseFloat("3.14"); // 3.14 |
? Examples
1. Convert Number to String
let x = 100;let str = x.toString(); // "100"2. Round to 2 Decimal Places
let pi = 3.14159;let rounded = pi.toFixed(2); // "3.14"3. Use Exponential Notation
let num = 987654;console.log(num.toExponential(3)); // "9.877e+5"4. Format to Precision
let value = 123.456;console.log(value.toPrecision(5)); // "123.46"? Type Conversion Methods
| Function | Description |
|---|---|
Number() | Converts to a number |
parseInt() | Parses and returns an integer |
parseFloat() | Parses and returns a floating number |
Number("123"); // 123parseInt("123.45"); // 123parseFloat("123.45"); // 123.45? Caution: toFixed() and toPrecision() return strings!
If you need the result as a number, convert it:
let n = Number((3.14159).toFixed(2)); // 3.14Want to see how to create custom rounding functions or format currency using number methods?