Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
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));

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!