Javascript
In JavaScript, numbers play a crucial role in performing various operations. They can be integers or floating-point values, and understanding their basics is essential.
// Example of integers
let integerNumber = 42;
// Example of floating-point numbers
let floatNumber = 3.14;
JavaScript provides predefined constants for commonly used numbers, making your code more readable.
| Constant | Description |
|---|---|
| Number.MAX_VALUE | Represents the maximum numeric value in JavaScript. |
| Number.MIN_VALUE | Represents the smallest positive numeric value. |
| Number.POSITIVE_INFINITY | Represents positive infinity. |
| Number.NEGATIVE_INFINITY | Represents negative infinity. |
| Number.NaN | Represents “Not a Number” value. |
| Number.EPSILON | Represents the difference between 1 and the smallest possible next representable number. |
Examples include Number.MAX_VALUE and Number.MIN_VALUE.
// Example of using number constants
console.log("Maximum value in JavaScript:", Number.MAX_VALUE);
console.log("Minimum positive value in JavaScript:", Number.MIN_VALUE);
JavaScript allows adding numbers and strings, but their types matter.
// Example of adding numbers and strings
let sum = 5 + "10"; // The result is a string "510"
console.log("Sum of 5 + '10':", sum);
Sometimes, numbers may appear as strings. Learn how to convert them to numerical values and vice versa for seamless manipulation.
// Example of converting numeric strings
let numericString = "42";
let numericValue = Number(numericString); // Convert string to number
console.log("Numeric value from string:", numericValue);
JavaScript uses NaN to represent the result of an undefined or unrepresentable mathematical operation.
// Example of NaN
let resultNaN = "hello" / 5; // This results in NaN
console.log("Result of 'hello' / 5:", resultNaN);
Here is the list of all the available methods of Numbers in Javascript.
| Method | Description |
|---|---|
| Number.toString() | Converts a number to a string. |
| Number.toFixed() | Formats a number using fixed-point notation. |
| Number.toPrecision() | Formats a number using specified precision. |
| Number.toExponential() | Converts a number to exponential notation. |
| Number.valueOf() | Returns the primitive value of a Number object. |
| Number.parseInt() | Parses a string argument and returns an integer. |
| Number.parseFloat() | Parses a string argument and returns a floating-point number. |
| Number.isNaN() | Checks if a value is NaN. |
| Number.isFinite() | Checks if a value is a finite number. |
| Number.isInteger() | Checks if a value is an integer. |
| Number.isSafeInteger() | Checks if a value is a safe integer. |