DEV Community

Shirley Li
Shirley Li

Posted on

Number.toString()

This short tutorial will go over a basic built-in method for the Number object in JavaScript, toString(). We will discuss what it is and how it can be used.

Number.toString()

The Number object has several built-in methods, one of which is the toString method. This method returns the String representation of the Number object.

let num1 = 10;
console.log(num1); // 10
console.log(num1.toString()); // "10"
Enter fullscreen mode Exit fullscreen mode

When the simple Number.toString() example above is run, the num1 will print out as the string "10".

Syntax

number.toString(radix);
Enter fullscreen mode Exit fullscreen mode

Number.toString() can take one optional parameter radix. radix can be any integer between 2 and 36. Any integers beyond this range will result in a RangeError when run. By default if no radix is specifed, base 10 is used.

let num2 = 213;
console.log(num2); // 213
console.log(num2.toString()); // "213"
console.log(num2.toString(2)); // "11010101"
console.log(num2.toString(16)); // "d5"
console.log(num2.toString(1)); // RangeError
Enter fullscreen mode Exit fullscreen mode

radix

radix, also referred to as base, is the number of unique symbols needed to represent numbers in a certain number system. For example, radix 2 refers to the binary number system. In that system, there are only 2 unique digits to represent numbers, 0 and 1. Similarly radix 16 uses 16 unique symbols (0-9 and A-F) to represent numbers. We use base 16 for hex colours.

Special Cases to Watch Out For

Numbers are not always positive integers. Sometimes we will run across the following situations:

  • Negative Number objects. When the Number object is negative, the "-" sign is not converted as part of the toString() method. Rather it can be viewed as putting the "-" back in place after running the toString() method.
let numPos = 549;
let numNeg = -549;
console.log(numPos.toString(16)); // "225"
console.log(numNeg.toString(16)); // "-225"
Enter fullscreen mode Exit fullscreen mode
  • Decimal Number objects. When the Number object is a decimal number, the "." is used to show the fractional portion.
let numDec = 17.56;
console.log(numDec.toString()); // "17.56"
Enter fullscreen mode Exit fullscreen mode

Conclusion

The toString()is useful when you want the object to be represented as readable text. Such situations include:

  • debugging
  • logging

I hope through this tutorial you were able to grasp a better understanding of Number.toString(). If you have time, I recommend familiarizing yourself with the other methods available on the Number object.

Top comments (0)