The number
data type is used for variables that will contain positive, negative or decimal numbers.
Operations
In JavaScript, a variable of type number
can easily be concatenated with another variable of type string
:
let myNumber = 30; myNumber = myNumber + "5"; .
However, this could lead to confusion and errors during program execution, in addition to changing the data type of the variable. Therefore, in TypeScript only numeric operations can be performed between numbers, for the sake of redundancy:
let myNumber: number = 30; myNumber = myNumber + 10; myNumber = myNumber + "10";
Use of uninitialized variables
- Those variables that we want to use without having given them an initial value will be marked as errors:
let productInStock: number;console.log("Product in stock: " + productInStock);
Note that if you are not going to initialize the variable yet, explicitly define the data type, because TypeScript cannot infer it if it does not have an initial value.
Conversion of numbers from string to number type
For this we will use the parseInt
method:
let discount: number = parseInt("123");let numberString: string = "100";let newNumber: number; newNumber = parseInt(numberString);
This works if the string has only and exclusively numbers that do not start with 0. Otherwise, the result will be of type NaN
(Not a Number):
let numeroTest: number = parseInt("word");console.log(numeroTest); .
Binary and Hexadecimal
TypeScript may give us errors if we try to define binary numbers that have numbers other than 0 or 1 and if we declare hexadecimals using out-of-range values:
let firstBinary = 0b1010; let secondbinary = 0b1210; let firstHexa = 0xfff; let secondHexa = 0xffz;
In console, if they are correctly assigned, a decimal conversion of those numbers will be done:
let firstHexa = 0xfff;console.log(firstHexa); let firstBinary = 0b1010;console.log(firstBinary);
Tip
When defining a variable of data type number
, it is preferable that the type name be lowercase. This is a good practice, because you will be referring to the data type number
and not to the language's own Number
object:
let myNumber: number = 20; let otherNumber: Number = 20;
Contribution created by: Martín Álvarez.
Want to see more contributions, questions and answers from the community?