;

TypeScript Number Type


TypeScript offers a powerful type system that helps developers write safe and predictable code. One of the fundamental types in TypeScript is the number type, which is used for numerical values in various forms like integers, floating-point numbers, and even more advanced representations. This tutorial will take you through everything you need to know about working with numbers in TypeScript, from basic concepts to advanced applications.

Introduction to TypeScript Number Types

In TypeScript, number is one of the core primitive types, used to represent numeric values in a way that is easy to work with and type-safe. TypeScript’s number type includes integers, floating-point values, and several numerical representations, making it flexible for a wide range of applications, from basic calculations to complex algorithms. 

Understanding the Number Type in TypeScript

In TypeScript, the number type encompasses all numeric values, including integers and floating-point numbers. When you declare a variable as a number, TypeScript ensures that only numeric values can be assigned to it.

Example: Basic Number Declaration

let age: number = 30;
let height: number = 5.9;

In this example, age and height are both number types, even though one is an integer and the other is a floating-point number. TypeScript does not distinguish between integer and floating-point values, treating them all as number.

Working with Number Literals

TypeScript allows you to declare numbers using several different literal formats. Let’s go over each one.

Integer Literals

Integer literals are whole numbers without any fractional part. TypeScript handles integers the same way as JavaScript, treating them as number types.

let count: number = 100;
let temperature: number = -5;

Floating-Point Literals

Floating-point literals are numbers with a decimal point, and they represent numbers with fractions.

let pi: number = 3.14;
let gravitationalConstant: number = 9.81;

Hexadecimal, Octal, and Binary Literals

TypeScript allows you to declare numbers in different bases using specific prefixes.

  • Hexadecimal: Prefix with 0x
  • Octal: Prefix with 0o
  • Binary: Prefix with 0b

Example: Declaring Numbers in Different Bases

let hex: number = 0xff; // Hexadecimal
let octal: number = 0o77; // Octal
let binary: number = 0b1010; // Binary

Using these formats is particularly useful in low-level programming or scenarios where specific binary or hexadecimal values are required.

Number Properties and Methods

TypeScript’s number type inherits properties and methods from JavaScript’s Number object. Here are some commonly used properties and methods.

Properties

  • Number.MAX_VALUE: The largest representable number.
  • Number.MIN_VALUE: The smallest positive number.
  • Number.POSITIVE_INFINITY: Represents positive infinity.
  • Number.NEGATIVE_INFINITY: Represents negative infinity.
  • Number.NaN: Represents “Not-a-Number” for invalid operations.

Example: Using Number Properties

console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.POSITIVE_INFINITY); // Infinity

Methods

  • toFixed(): Rounds a number to a specified number of decimal places.
  • toExponential(): Converts a number to exponential notation.
  • toPrecision(): Formats a number to a specified length.

Example: Using Number Methods

let value: number = 123.456;

console.log(value.toFixed(2)); // "123.46"
console.log(value.toExponential(1)); // "1.2e+2"
console.log(value.toPrecision(4)); // "123.5"

These methods can be helpful for formatting numbers, especially in financial applications or when displaying large numbers to users.

Advanced Number Types

BigInt Type

While TypeScript’s number type can represent large values, there’s a limit to its precision. For extremely large integers, TypeScript offers the BigInt type, which allows precise representation of integers beyond Number.MAX_SAFE_INTEGER.

Example: Declaring a BigInt

let largeNumber: bigint = 123456789012345678901234567890n;

In TypeScript, BigInt values are represented with a suffix n. Note that arithmetic operations between number and BigInt types are not allowed directly, so you may need to convert them explicitly if necessary.

NaN and Infinity

NaN (Not-a-Number) and Infinity are special values within the number type.

  • NaN: Represents an invalid or unrepresentable value, such as the result of dividing zero by zero.
  • Infinity: Represents infinity. It can be positive or negative, as shown in Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY.

Example: Using NaN and Infinity

let invalidOperation: number = 0 / 0; // NaN
let largeValue: number = 1 / 0;       // Infinity

console.log(isNaN(invalidOperation)); // true
console.log(largeValue);              // Infinity

NaN and Infinity are useful for handling edge cases in numerical calculations, such as division by zero or invalid mathematical operations.

Real-World Examples of Using Number Types

Example 1: Calculating Area of a Circle

In applications that involve geometry or physics, using numbers is essential. For instance, you might need to calculate the area of a circle.

function calculateCircleArea(radius: number): number {
  const pi: number = 3.14159;
  return pi * radius * radius;
}

let radius = 5;
console.log(`Area of circle: ${calculateCircleArea(radius).toFixed(2)}`);

In this example:

  • pi is a constant value for the calculation.
  • The result is rounded to two decimal places using toFixed().

Example 2: Temperature Conversion Application

In applications dealing with temperature data, conversions are often required. Here’s an example of converting Fahrenheit to Celsius.

function fahrenheitToCelsius(fahrenheit: number): number {
  return ((fahrenheit - 32) * 5) / 9;
}

let temperature = 98;
console.log(`Temperature in Celsius: ${fahrenheitToCelsius(temperature).toFixed(2)}`);

This example shows a simple temperature conversion formula, formatted to two decimal places for user-friendliness.

Example 3: Using BigInt for Precise Calculations

In financial or scientific applications, large integers are sometimes needed. BigInt provides a way to work with such large values without losing precision.

let largeAmount: bigint = 10000000000000000000n;
let additionalAmount: bigint = 20000000000000000000n;

let totalAmount: bigint = largeAmount + additionalAmount;
console.log(`Total Amount: ${totalAmount}`);

By using BigInt, this example ensures that large numbers are calculated precisely, which is crucial in scenarios like financial calculations.

Key Takeaways

  1. TypeScript number Type: TypeScript’s number type includes integers, floating-point numbers, and values in hexadecimal, octal, and binary.
  2. Useful Properties and Methods: Properties like Number.MAX_VALUE and methods like toFixed() and toPrecision() help manage and format numeric values.
  3. BigInt for Large Integers: BigInt is ideal for precise calculations with extremely large integers, ensuring accuracy beyond the regular number type.
  4. NaN and Infinity for Edge Cases: Special values like NaN and Infinity handle cases like division by zero and invalid operations.
  5. Real-World Applications: Number types in TypeScript are applicable across various fields, from geometry to finance and data analysis.

Summary

TypeScript’s number types provide robust support for handling various numerical values and operations, ranging from simple integers to large integers with BigInt. This tutorial covered basic and advanced number types, useful properties and methods, and real-world examples. By understanding these concepts, you can handle numeric data more effectively in TypeScript, ensuring that your applications are accurate, reliable, and user-friendly.