📜  TypeScript-数字(1)

📅  最后修改于: 2023-12-03 15:35:24.767000             🧑  作者: Mango

TypeScript-数字

Introduction

TypeScript is a superset of JavaScript that provides strong typing for variables and objects. It allows developers to catch errors early and write more maintainable code. TypeScript supports different types of data, including numbers.

Number types in TypeScript
Number

The number type in TypeScript represents all types of numbers, including integers and floating-point numbers. For example:

let age: number = 28;
let price: number = 4.99;
BigInt

TypeScript also supports the bigint type, which is used to represent integers larger than Number.MAX_SAFE_INTEGER. For example:

let bigNumber: bigint = 9999999999999999n;
Math functions

TypeScript provides built-in functions for mathematical operations, including:

  • Math.abs: returns the absolute value of a number.
  • Math.ceil: returns the smallest integer greater than or equal to a number.
  • Math.floor: returns the largest integer less than or equal to a number.
  • Math.max: returns the largest of zero or more numbers.
  • Math.min: returns the smallest of zero or more numbers.
  • Math.pow: returns the result of raising a number to a specified power.
  • Math.random: returns a random number between 0 and 1.
  • Math.round: returns the value of a number rounded to the nearest integer.

For example:

let num: number = -10.5;
console.log(Math.abs(num)); // output: 10.5
console.log(Math.ceil(num)); // output: -10
console.log(Math.floor(num)); // output: -11
console.log(Math.max(1, 2, 3)); // output: 3
console.log(Math.min(1, 2, 3)); // output: 1
console.log(Math.pow(2, 3)); // output: 8
console.log(Math.random()); // output: a random number between 0 and 1
console.log(Math.round(num)); // output: -11
Conclusion

TypeScript's support for strong typing and built-in mathematical functions makes it a powerful language for developers working with numbers. Understanding the different number types and functions available in TypeScript is essential for writing efficient and maintainable code.