Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  89] [ 7]  / answers: 1 / hits: 20367  / 14 Years ago, sun, february 20, 2011, 12:00:00

I would like to convert a number in base 10 with fraction to a number in base 16.


var myno = 28.5;

var convno = myno.toString(16);
alert(convno);

All is well there. Now I want to convert it back to decimal.


But now I cannot write:


var orgno = parseInt(convno, 16);
alert(orgno);

As it doesn't return the decimal part.


And I cannot use parseFloat, since per MDC, the syntax of parseFloat is


parseFloat(str);

It wouldn't have been a problem if I had to convert back to int, since parseInt's syntax is


parseInt(str [, radix]);

So what is an alternative for this?


Disclaimer: I thought it was a trivial question, but googling didn't give me any answers.


This question made me ask the above question.


More From » numbers

 Answers
70

Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together.




function parseFloat(str, radix)
{
var parts = str.split(.);
if ( parts.length > 1 )
{
return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length);
}
return parseInt(parts[0], radix);
}

var myno = 28.4382;
var convno = myno.toString(16);
var f = parseFloat(convno, 16);
console.log(myno + -> + convno + -> + f);




[#93663] Thursday, February 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aliah

Total Points: 118
Total Questions: 132
Total Answers: 94

Location: Tajikistan
Member since Fri, Sep 11, 2020
4 Years ago
;