Javascript中的Java数字精度 [英] Java number precision in Javascript

查看:51
本文介绍了Javascript中的Java数字精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有以下代码将十六进制值转换为长数字,在示例中,我使用了该值:'B4EEB49B04C0'

I have the following code in Java that convert Hex values to Long numbers, in the example I used the value: 'B4EEB49B04C0'

public static long HexStr2Long(String value)
{
    value = value.toUpperCase();
    long result = 0;
    for (int i = 0; i < value.length(); i++)
    {
        int x = value.length() - i - 1;
        char ch = value.charAt(i);
        result += keys.indexOf(ch) * Pow(exponent, x);
    }
    return result;
}

public static long Pow(long baseNo, long x)
{
    long value = 1;
    while (x > 0)
    {
        value = value * baseNo;
        x--;
    }
    return value;
}

public static void main(String[] args) {
    long result = HexStr2Long("B4EEB49B04C0");
    System.out.print("resultado: "+result+"\n");
}

结果是:1463925582232863984

The result is: 1463925582232863984

现在,我用Javascript创建了等效的代码:

Now, I created the equivalent code in Javascript:

pow = function(baseNo, x){
  var value = 1;
  while(x > 0){
    value = value * baseNo;
    x--;
  }

  return value;
}

hexStr2Long = function(val){
 var keys = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var exponent = keys.length;

 val = val.toUpperCase();
 var result = 0;
 for (var i = 0; i < val.length; i++) {
    var x = val.length - i - 1;
    var ch = val.charAt(i);
    result +=  keys.indexOf(ch) * Math.pow(exponent, x);
 }

 return result;
}
var r = hexStr2Long(wifimac);
console.log('Result: '+r);

结果是:1463925582232864000,这个错了,必须和Java代码一样.

The result is: 1463925582232864000, this in wrong, it has to be the same as Java code.

我该怎么做?我已经尝试使用该库( BigNumber ),但没有成功.

How can I accomplish that? I've already tried to use the library (BigNumber) but without success.

推荐答案

1463925582232864000是距离1463925582232863984984最近的64位IEEE-754浮点数.Javascript中的数字始终是(此刻-我认为这是在改变)64位IEEE-754浮点数.

1463925582232864000 is the nearest 64-bit IEEE-754 floating point number to 1463925582232863984. Numbers in Javascript are (at the moment - I believe this is changing) always 64-bit IEEE-754 floating point numbers.

基本上,要执行此操作,您需要一个Javascript库,该库支持内置的数字类型 other .(我希望BigNumber可以工作,但是您没有向我们展示您尝试了什么,所以很难知道您做错了.)

Basically, in order to do this you'll need a Javascript library that supports numeric types other than what's built in. (I'd expect BigNumber to work, but you haven't shown us what you tried with it, so it's hard to know what you did wrong.)

这篇关于Javascript中的Java数字精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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