We will get used to using Number.toString() in TypeScript to receive a string that represents the number we put in. This method is often used when there is a demand to convert a number to a string in TypeScript.
Using Number.toString() in TypeScript
Converting integer numbers to string
A string that represents the given object is returned by this method. This method convert the number object to a string representing that number in the given radix (base) and return it:
- radix: An integer between 2 and 36 specifying the base to use for representing numeric values.
var x = new Number(99); console.log(x.toString()); console.log(x.toString(2)); console.log(x.toString(16));
99 1100011 63
The logic behind this method is very simple because the Number object will override the toString() function of the Number Object. As a result, the toString() function returns a string representing the value of the Number object in the given radix. If you pass a negative number to the Number.toString() method, the sign will be preserved:
const x = -999; const y = -9; console.log(x.toString()); console.log(y.toString(2));
This is an example when the radix is 2 (binary); the returned string is the positive base 2 representation of the number Object preceded by a minus sign (-), not in the 2’s complement format.
If a floating point number is passed to the Number.toString() method, the decimal will be preserved.
const x = -99.009; const y = 1.000; console.log(x.toString()); console.log(y.toString());
The (.) sign in the string is preserved.
Converting radix of number strings
Using parseInt() and toString(), you may change the radix of a string that represents a number in a non-decimal radix.
- substring: a string that begins with an integer. In this argument, leading whitespace is disregarded.
- radix: A number between 2 and 36 that specifies the base to utilize for expressing numerical values is referred to.
const hex = "ABA"; const bin = parseInt(hex, 16).toString(2); console.log(bin)
The toString() function attempts to return a string representation in the chosen radix after parsing its first input (base). The letters of the alphabet denote numbers larger than 9 for radices above 10. For instance, the letters a to f are used for hexadecimal numerals (base 16).
Avoid losing precision by using a BigInt instead of the current number string if it is too long (bigger than Number.MAX SAFE INTEGER, for example).
We have learned about two different approaches in the article “using Number.toString() in TypeScript“. It would help if you considered that each approach depends on your choices. By passing a correct number value to the toString() method, we can receive a string representing that number.
Maybe you are interested:
- Concatenate a String and a Number in TypeScript
- Check if String is a Valid Number in TypeScript
- Convert a Number to a String in TypeScript
Name of the university: HCMUT