TypeScript Number

TypeScript, like JavaScript, supports numbers as a fundamental data type. These numbers can represent both integers and floating-point values. Understanding how to work with numbers efficiently is crucial for various tasks in TypeScript development. Let's look into a detailed explanation of TypeScript numbers with examples.

Number Representation

In TypeScript, all numbers are stored internally as 64-bit double-precision floating-point values according to the IEEE 754 standard. This means they can represent a vast range of values, from very small to very large, with some limitations in precision for certain values.

Number Literals

Numbers can be defined directly using literal values. TypeScript supports several formats for number literals:

  1. Decimal: 1, 10, 100
  2. Binary: 0b1010 (prefixed with "0b")
  3. Octal: 0o123 (prefixed with "0o")
  4. Hexadecimal: 0xAF (prefixed with "0x")

Number Declaration and Initialization

Numbers can be declared and initialized like this:

let integerNumber: number = 42; let floatingPointNumber: number = 3.14;

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

let integerNumber = 42; let floatingPointNumber = 3.14;

TypeScript automatically infers the type based on the assigned value, but explicit type annotations, as shown, can be used for clarity.

Arithmetic Operations

TypeScript supports standard arithmetic operations like addition, subtraction, multiplication, and division.

let sum: number = 10 + 5; // 15 let difference: number = 20 - 8; // 12 let product: number = 7 * 3; // 21 let quotient: number = 15 / 2; // 7.5

Modulo Operator (%)

The modulo operator returns the remainder of a division.

let remainder: number = 15 % 2; // 1

Increment and Decrement

TypeScript supports increment (++) and decrement (--) operators.

let counter: number = 5; counter++; // Increment by 1 let newCounter: number = counter--; // Decrement by 1

NaN and Infinity

NaN represents "Not a Number," and Infinity represents positive infinity.

let notANumber: number = NaN; let positiveInfinity: number = Infinity;

Number Type Annotations

TypeScript allows using type annotations to specify the expected type of a number variable or function parameter. This helps ensure type safety and avoid errors.

let age: number = 30; // age is expected to be a number function sum(a: number, b: number): number { return a + b; // function expects two numbers as arguments and returns a number }

Typescript Number Properties

The Number object provides several properties related to numbers. These properties offer information about the range and precision of representable numeric values.

Number.MAX_VALUE and Number.MIN_VALUE

  1. Number.MAX_VALUE represents the maximum positive representable value in JavaScript.
  2. Number.MIN_VALUE is the minimum positive representable value greater than zero.
let maxNumber: number = Number.MAX_VALUE; // Maximum positive representable number let minNumber: number = Number.MIN_VALUE; // Minimum positive representable number greater than 0

These values are useful for understanding the limits of numeric representation in JavaScript.

Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY

Number.POSITIVE_INFINITY represents positive infinity, while Number.NEGATIVE_INFINITY represents negative infinity.

let positiveInfinity: number = Number.POSITIVE_INFINITY; // Positive infinity let negativeInfinity: number = Number.NEGATIVE_INFINITY; // Negative infinity

These values are encountered in computations that result in overflow or underflow.

Number.NaN (Not a Number)

Number.NaN represents a value that is not a valid number. It is commonly used to indicate the result of an invalid or undefined mathematical operation.

let notANumber: number = Number.NaN; // Represents "Not a Number"

Checking for NaN is often used to identify failed numeric operations.

Example Using Properties:

Demonstrating the use of these properties in a practical example:

let maxNumber: number = Number.MAX_VALUE; let minNumber: number = Number.MIN_VALUE; let positiveInfinity: number = Number.POSITIVE_INFINITY; let notANumber: number = Number.NaN; console.log(`Max Number: ${maxNumber}`); console.log(`Min Number: ${minNumber}`); console.log(`Positive Infinity: ${positiveInfinity}`); console.log(`Not a Number: ${notANumber}`);

Running this code would display information about the maximum and minimum representable values, positive infinity, and "Not a Number."

Typescript Number Methods

The Number object provides various built-in methods for performing common operations on numeric values. These methods are accessible through the Math object. Let's explore some of the commonly used number methods with examples:

Math.abs(x: number)

Returns the absolute value of a number.

let absoluteValue: number = Math.abs(-7); // Returns 7

Math.round(x: number)

Rounds a number to the nearest integer.

let roundedValue: number = Math.round(3.75); // Returns 4

Math.ceil(x: number): number and Math.floor(x: number)

  1. Math.ceil rounds a number up to the nearest integer.
  2. Math.floor rounds a number down to the nearest integer.
let ceilValue: number = Math.ceil(3.2); // Returns 4 let floorValue: number = Math.floor(3.8); // Returns 3

Math.random()

Returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

let randomValue: number = Math.random(); // Returns a random value between 0 and 1

You can use this method to generate random numbers for various purposes.

Math.pow(x: number, y: number)

Returns the result of raising a number to a specified power.

let power: number = Math.pow(2, 3); // Returns 8 (2^3)
Example Using Number Methods:

Demonstrating the use of these methods in a practical example:

let numberToManipulate: number = -3.14159; let absolute: number = Math.abs(numberToManipulate); let rounded: number = Math.round(numberToManipulate); let ceiling: number = Math.ceil(numberToManipulate); let flooring: number = Math.floor(numberToManipulate); let random: number = Math.random(); console.log(`Absolute Value: ${absolute}`); console.log(`Rounded Value: ${rounded}`); console.log(`Ceiling Value: ${ceiling}`); console.log(`Flooring Value: ${flooring}`); console.log(`Random Value: ${random}`);

Conclusion

The number type is used to represent both integer and floating-point numeric values. It supports standard arithmetic operations, as well as additional functionalities provided by the Math object, offering methods for absolute values, rounding, random number generation, and more. The language also provides properties like Number.MAX_VALUE and Number.MIN_VALUE to understand the limits of numeric representation.