user17386646
user17386646

Reputation:

float number conversions with ".toString" is funcional in JavaScript?

For example, if I convert number 1.1 to binary (or any other number base) is it possible to return it to decimal float number?

console.log((1.1).toString(2));
console.log((1.1).toString(8));
console.log((1.1).toString(16));

Upvotes: 0

Views: 57

Answers (1)

CRice
CRice

Reputation: 32186

JS has a few built in methods for parsing numbers. Using parseFloat here would be ideal, however unfortunately parseFloat does not allow you to specify the radix (base) under which the string should be parsed.

However, the parseInt function does let you specify the radix, but it can only work with integer numbers and will fail when trying to parse a decimal. But with a little bit of math you can parse the whole and decimal parts of your string separately, then recombine them to get the converted number.

Perhaps something like:

console.log((1.1).toString(2));
console.log((1.1).toString(8));
console.log((1.1).toString(16));

function parseInBase(num_str, base) {
  const [integer_part, decimal_part] = num_str.split(".");
  const integer_part_num = parseInt(integer_part, base);
  
  if (!decimal_part) return integer_part_num;
  
  // Trim trailing zeroes:
  const sanitized_dec_part = decimal_part.replace(/0+$/, "");
  const decimal_part_num = parseInt(sanitized_dec_part, base);
  
  return integer_part_num + decimal_part_num / base**sanitized_dec_part.length;
}

console.log(parseInBase((1.1).toString(2), 2));
console.log(parseInBase((1.1).toString(8), 8));
console.log(parseInBase((1.1).toString(16), 16));

Upvotes: 1

Related Questions