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

查看:66
本文介绍了在 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);

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

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