Javascript 长整数 [英] Javascript long integer

查看:28
本文介绍了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;
   }

我返回一个 long 值并且:

I return a single long value and:

$.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天全站免登陆