js 单精度浮点数转10进制,在javascript中将十六进制转换为浮点数

This question made me ask the below question.

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 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 syntax is

parseInt(str [, radix]);

So what is an alternative for this?

Disclaimer: I thought it was a trivial question but googling gave me no answers.

解决方案

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

alert(myno + " -> " + convno + " -> " + f );

你可能感兴趣的:(js,单精度浮点数转10进制)