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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值