在 JavaScript 中将十六进制转换为浮点数

2022-01-17 00:00:00 numbers hex javascript

我想将带分数的以 10 为底的数字转换为以 16 为底的数字.

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.

但现在我不能写了:

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

因为它不返回小数部分.

As it doesn't return the decimal part.

而且我不能使用 parseFloat,因为根据 MDC,parseFloat 的语法是

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

parseFloat(str);

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

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.

这个问题让我问了上面的问题.

推荐答案

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

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

相关文章