37

I'm just wondering what it means to attach a number as a parameter to the toString() method

E.g. obj.toString(10);

I googled and i have never seen a parameter before.

one noa
  • 345
  • 1
  • 3
  • 10
Dennis D
  • 1,293
  • 4
  • 17
  • 24

3 Answers3

37

The additional parameter works only for Number.prototype.toString to specify the radix (integer between 2 and 36 specifying the base to use for representing numeric values):

var number = 12345;
number.toString(2) === "11000000111001"
number.toString(3) === "121221020"
// …
number.toString(36) === "9ix"
Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 1
    MDN gives a pretty good explanation on the subject: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString – luissquall Aug 15 '12 at 03:07
15

This only works on Number objects and is intended to give you a way of displaying a number with a certain radix:

var n = 256;
var d = n.toString(10); // decimal: "256"
var o = n.toString(8);  // octal:   "400"
var h = n.toString(16); // hex:     "100"
var b = n.toString(2);  // binary:  "100000000"
var w = n.toString(20); // base 20: "cg"

Note that the radix must be an integer between 2 and 36 or toString() will raise an error.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Late comment on this, and it was to short of an edit to make. But `var b = n.toString(16); // binary: "100000000"` should actually be `n.toString(2)` since binary is in base 2, I assume it was just a copy paste thing! – Rchristiani Nov 08 '12 at 18:08
  • @Rchristiani Absolutely. An edit would have been perfectly in order, but now I've changed it myself. Thanks for the hint! – Tomalak Nov 08 '12 at 20:41
4

It's not defined as a globally-applicable argument to toString, it only makes sense on Number, where it specifies the base to write in. You can use eg. n.toString(16) to convert to hex.

The other built-in objects don't use any arguments and JavaScript will silently ignore unused arguments, so passing 16 to any other toString method will make no difference. You can of course make your own toString methods where optional arguments can mean anything you like.

bobince
  • 528,062
  • 107
  • 651
  • 834