For example, dividing to any number by 0 returns infinity as shown below:
Note: Infinity is a special value and it represents the mathematical Infinity ∞, which is greater than any number. The typeof operator returns the number for an Infinity value.
Avoiding Precision Problems:
Sometimes while performing operations on floating-point numbers produce unexpected results, as shown below:
In the above example, the result is 0.30000000000000004 rather than the expected 0.3. This difference in the result is called representation error or roundoff error.
To avoid such problem you can use the solution given below:
Performing Operations on Numbers:
Parsing Integers from Strings:
The parseInt() method is used to parse an integer from a string. If this method encounters a character that is not numeric in the specified base, it stops parsing and returns the integer value parsed up to that point. If the first character cannot be converted into a number, the parseInt() method will return NaN (not a number).
Similarly, the parseFloat() method can be used to parse floating-point numbers from a string. This method works the same way as the parseInt() method, the only difference is that it retrieves both integers and numbers with decimals.
Converting Numbers to Strings:
The toString() method is used to convert a number to its string equivalent. This method accepts an integer parameter optionally in the range 2 through 36 specifying the base to use for representing numeric values.
The following example shows the number to string conversion.
Formatting Numbers in Exponential Notation:
The toExponential() method is used to format or represent a number in exponential notation. The toExponential() method optionally accepts an integer parameter specifying the number of digits after the decimal point. Also, the returned value is a string, not a number.
Note: Exponential notation is used to represent the numbers that are either very large or very small in magnitude. For example, 12300000000 can be written as 123e+8 or 1.23e+10.
Formatting Numbers to Fixed Decimals:
The toFixed() method is used when you want to format a number with a fixed number of digits to the right of the decimal point. The value returned by toFixed() method is a string and it has exactly specified the number of digits after the decimal point. If the digits parameter is not specified then it is treated as 0.
Formatting Numbers with Precision:
The toPrecision() method is used when you want the most appropriate form of a number. The toPrecision() method is used to return a string representing the number to the specified precision.
Finding the Largest and Smallest Possible Numbers:
Finding Positive and Negative Infinity:
The Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY method is used to represent a number that falls outside of the range of possible numbers.