.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 two parameters:

  • current base: The base a string or number is currently in (between 2 and 36)

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

Usage On Numbers

num = 255

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

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

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

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

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

// Converting from an abnormal base to decimal also works.
hex = "ff"
log hex.toBase(16, 10)
// "255"

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

It's important to remember that the output will always be a string; if converting from an abnormal base to a decimal, that decimal must be converted into a number for use in equations.

Last updated

Was this helpful?