.toBase(base)

Description

toBase converts a number to a string representation in the specified base (radix). Common uses include converting to binary (base 2), octal (base 8), or hexadecimal (base 16).

Parameters

toBase needs one parameter:

  • base: The base to convert the number to (between 2 and 36)

Usage On Numbers

num = 255

log num.toBase(16)
// "ff"
// converts to hexadecimal

log num.toBase(2)
// "11111111"
// converts to binary

log num.toBase(8)
// "377"
// converts to octal

num = 15
log num.toBase(16)
// "f"
// single digit hex number

// Can be used with any base from 2 to 36
num = 42
log num.toBase(36)
// "16"
// maximum base using 0-9 and a-z

// Negative numbers are supported
num = -255
log num.toBase(16)
// "-ff"

Last updated

Was this helpful?