JavaScript: int to string

Javascript Int String

Every built-in JavaScript object type has a toString() method. This method is automatically called when the object needs to be represented as a string value (i.e., when you concatenate some string value with a number), or it can be called manually when such a type conversion is wanted.

The toString() method works on all of the standard JS objects: arrays, dates, numbers, errors, et cetera. For number types, the toString() method also can take an optional “radix” argument: number.toString(radix)

The radix (or base) is the total number of unique digits, including zero, that are used to represent a particular number system. For number systems other than the decimal system, you can use the radix argument to correctly stringify a number from some other number system, such as the octal (base 8) and hexadecimal (base 16) number systems.

Here are some examples of the toString() method being used on numbers:

var x = 10; // integer number
var y = 7.950; // floating point number
var z = 1.21e–6; // floating point number in a scientific notation
var inf = Number.POSITIVE_INFINITY; // infinity

console.log(‘hello’ + x); // 'hello10' - toString() is called automatically
console.log(x.toString()); // “10” - decimal base
console.log(x.toString(2)); // “1010” - binary base
console.log(x.toString(8)); // “12” - octal base
console.log(x.toString(16)); // “a” - hex base

console.log(y.toString()); // “7.95” - note the stripped “0” at the end
console.log(y.toString(2)); // “111.11110011001100111000011100010110000010010101011011”
console.log(y.toString(16)); // “7.f33387160956c”

console.log(z.toString()); // “0.00000121”

console.log(inf.toString()); // “Infinity”
console.log(inf.toString(2)); // “Infinity”

There isn’t really much more to using toString() on numbers in JavaScript. As always, if you have any questions, ask away in a comment below.