Javascript长整数 [英] Javascript long integer

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

问题描述

我在javascript中看到了一个最奇怪的事情。
服务器端(spring):

I have seen one of the weirdest things in javascript. The server side (spring):

   @RequestMapping(value = "/foo", method = RequestMethod.GET)
   @ResponseBody
   public Long foo() {
      return 793548328091516928L;
   }

我返回一个长值并且:

$.get('/foo').done(function(data){
    console.log(data);
});

它表示长整数为793548328091516900,用0替换(确实舍入)最后两位数字。当我从任何浏览器的地址栏发出GET请求时,数字表示正确;因此,在我看来,这是一个js问题。

It represents the long integer as "793548328091516900" replacing (rounding indeed) the last two digits with 0s. When i make that GET request from any browser's address bar, the number represented correctly; thus this is a js issue, in my opinion.

从服务器返回一个字符串而不是long并使用以下代码处理它:

Returning a string instead of long from server and handling it with:

var x = new Number(data).toFixed();

显然是一个解决方案。但我不是很幸运,我必须处理一个复杂的POJO(转换为JSON),其中一些字段(一些是嵌套的)是用 java.lang.Long 类型键入的。如果我尝试将此POJO转换为另一个对象没有字段键入Long,则显然很麻烦。

obviously a solution. But I am not so lucky that, I have to handle a complex POJO (converted to JSON) whose some fields (some are nested) are typed with java.lang.Long type. If i try to cast this POJO to another object does not having fields typed Long, it is obviously cumbersome.

是否有更明确的解决方案?

Is there any solution to that obstacle in a clearer way?

推荐答案

在Java中,你有64位整数,这就是你正在使用的。

In Java, you have 64 bits integers, and that's what you're using.

在JavaScript中,所有数字都是 64位浮点数。这意味着您无法在JavaScript中表示所有Java长度。尾数的大小约为53位,这意味着您的数字 793548328091516928 无法准确表示为JavaScript编号。

In JavaScript, all numbers are 64 bits floating point numbers. This means you can't represent in JavaScript all the Java longs. The size of the mantissa is about 53 bits, which means that your number, 793548328091516928, can't be exactly represented as a JavaScript number.

如果你真的需要处理这些数字,你必须以另一种方式代表它们。这可以是字符串,也可以是数字数组之类的特定表示。 JavaScript中提供了一些大数字库。

If you really need to deal with such numbers, you have to represent them in another way. This could be a string, or a specific representation like a digit array. Some "big numbers" libraries are available in JavaScript.

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

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