在javascript中将十六进制转换为浮点数 [英] Converting hexadecimal to float in javascript

查看:954
本文介绍了在javascript中将十六进制转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题让我问下面的问题。



我想将基数为10的数字转换为基数为16的数字。

  var myno = 28.5; 

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

一切都很好。现在我想把它转换回十进制。

但是现在我不能写
$ b $ $ pre $ var $ or $ gt; $ or $ gt; parseInt (convno,16);
alert(orgno);

因为它不返回小数部分。



不能使用parseFloat,因为每个MDC的parseFloat的语法是

  parseFloat(str); 

如果我必须转换回int,这不会是个问题,因为parseInt语法是

  parseInt(str [,radix]); 

那么这是什么选择?

免责声明:我认为这是一个微不足道的问题,但谷歌搜索给了我没有答案。

解决方案

另一种可能性是解析数字分开,将字符串分成两部分,在转换过程中将这两部分视为整数,然后将它们一起添加回去。

  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]。长度);
}
return parseInt(parts [0],radix);
}

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


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

这篇关于在javascript中将十六进制转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆