JavaScript String Representations of Numbers


Example

JavaScript has native conversion from Number to it's String representation for any base from 2 to 36.

The most common representation after decimal (base 10) is hexadecimal (base 16), but the contents of this section work for all bases in the range.


In order to convert a Number from decimal (base 10) to it's hexadecimal (base 16) String representation the toString method can be used with radix 16.

// base 10 Number
var b10 = 12;

// base 16 String representation
var b16 = b10.toString(16); // "c"

If the number represented is an integer, the inverse operation for this can be done with parseInt and the radix 16 again

// base 16 String representation
var b16 = 'c';

// base 10 Number
var b10 = parseInt(b16, 16); // 12

To convert an arbitrary number (i.e. non-integer) from it's String representation into a Number, the operation must be split into two parts; the integer part and the fraction part.

6
let b16 = '3.243f3e0370cdc';
// Split into integer and fraction parts
let [i16, f16] = b16.split('.');

// Calculate base 10 integer part
let i10 = parseInt(i16, 16); // 3

// Calculate the base 10 fraction part
let f10 = parseInt(f16, 16) / Math.pow(16, f16.length); // 0.14158999999999988

// Put the base 10 parts together to find the Number
let b10 = i10 + f10; // 3.14159

Note 1: Be careful as small errors may be in the result due to differences in what is possible to be represented in different bases. It may be desirable to perform some kind of rounding afterwards.
Note 2: Very long representations of numbers may also result in errors due to the accuracy and maximum values of Numbers of the environment the conversions are happening in.