TypeScript Number Object
In TypeScript, number is a primitive data type used to represent numbers, including integers and floating-point numbers. In addition to this primitive type, there is a corresponding built-in object Number. The Number object is a wrapper object for the primitive number type, providing some properties and methods for working with numbers.
Typically, using the number type directly is sufficient. When you call a method on a number type variable (like toFixed()), JavaScript/TypeScript automatically wraps it in a temporary Number object behind the scenes to perform the operation.
Properties of the Number Object
The Number object provides some useful built-in properties that are static and can be accessed directly through Number.
-
Number.MAX_VALUE: Represents the largest positive number that can be represented in JavaScript. -
Number.MIN_VALUE: Represents the smallest positive number that can be represented in JavaScript (the positive number closest to 0). -
Number.NaN: Represents the special "Not-a-Number" value. When an arithmetic operation returns an undefined or unrepresentable value, you getNaN. -
Number.POSITIVE_INFINITY: Represents positive infinity. -
Number.NEGATIVE_INFINITY: Represents negative infinity.
Methods of the Number Object
These methods need to be called through an instance of the number type.
-
toFixed(digits): Formats a number to a string with a specified number of decimal places. It performs rounding. -
toPrecision(precision): Formats a number to a string with a specified total length (significant digits). It also performs rounding. -
toString(radix): Converts a number to a string representation in the specified base (radix).radixis an integer between 2 and 36. If omitted, defaults to 10. -
toExponential(fractionDigits): Returns a string representing the number in exponential notation.fractionDigitsis optional and specifies the number of digits in the fractional part. -
toLocaleString(): Returns a localized string representation of the number. This is useful when displaying currency, dates, etc., as it formats numbers according to the user's locale settings.
These methods provide powerful flexibility for handling and displaying numbers.