Typescript number
Created By: chatGPT
TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. Working with numbers in TypeScript is similar to JavaScript, but it offers better type safety. Here's how you can declare and use numbers in TypeScript.
let age: number = 25;
let temperature: number = -10.5;
const pi: number = 3.14;
You can also use arithmetic operators for calculations. TypeScript supports all the standard arithmetic operations like addition, subtraction, multiplication, and division.
let sum: number = age + 5;
let product: number = age * 2;
let division: number = temperature / 2;
TypeScript also allows the use of template literals for formatting numbers. You can embed expressions within a string using backticks.
let formattedString: string = `Your age is ${age} years.`;
console.log(formattedString);
let temperatureString: string = `The current temperature is ${temperature}°C.`;
console.log(temperatureString);
If you want to perform more advanced numeric operations, you can utilize the Math object provided by JavaScript, which is fully available in TypeScript as well.
let randomNumber: number = Math.random();
let squareRoot: number = Math.sqrt(16);
let roundedValue: number = Math.round(3.7);
TypeScript enables you to work with integers and floating-point numbers seamlessly, but you need to be cautious when dealing with floating-point precision issues.
let preciseValue: number = 0.1 + 0.2;
console.log(preciseValue === 0.3); // Output: false
let correctedValue: number = Math.round((0.1 + 0.2) * 10) / 10;
console.log(correctedValue === 0.3); // Output: true