Code Logo

Base Conversion with toString(radix)

Published at25 Jul 2026
JavaScript Functions Easy 0 views
Like0

Write a JavaScript function that takes a decimal number and a radix (base), and returns the number converted to that base as a string using Number.toString(radix). The radix can be between 2 and 36.

Number.prototype.toString(radix) converts a number to its string representation in the specified base. The radix parameter must be an integer between 2 and 36. When radix is 2, the number is converted to binary. When radix is 16, it's hexadecimal. When radix is 8, it's octal. Without a radix, decimal (base 10) is assumed.

This method is the standard way to perform base conversion in JavaScript. It handles fractional numbers, negative numbers, and very large numbers. For bases above 10, letters a-z are used as digits (a=10, b=11, ..., z=35). The method is complementary to parseInt() which converts strings from a given radix back to numbers.

Time complexity is O(log n) where n is the number value, as the algorithm repeatedly divides by the radix. Space complexity is O(log n) for the resulting string length. The result is always lowercase for bases above 10.

Edge cases include base 2 (binary with only 0 and 1 digits), base 16 (hexadecimal with a-f digits), base 10 (same as default), and ensuring the radix is within the valid 2-36 range.

Example Input & Output

Example 1
Input
100,16
Output
"64"
Explanation

100 decimal = 64 hex

Example 2
Input
42,10
Output
"42"
Explanation

42 decimal = 42 decimal

Example 3
Input
15,8
Output
"17"
Explanation

15 decimal = 17 octal

Example 4
Input
10,2
Output
"1010"
Explanation

10 decimal = 1010 binary

Example 5
Input
255,16
Output
"ff"
Explanation

255 decimal = ff hexadecimal

Algorithm Flow

Recommendation Algorithm Flow for Base Conversion with toString(radix)
Recommendation Algorithm Flow for Base Conversion with toString(radix)

Solution Approach

function solution(num, radix) {
  return num.toString(radix);
}

Best Answers

javascript - Approach 1
function solution(num, radix) {
  return num.toString(radix);
}