Converting hexadecimal to float in JavaScript(在 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 中将十六进制转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中将十六进制转换为浮点数
基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01