【问题标题】:How to avoid rounding of a long value on client side?如何避免在客户端舍入长值?
【发布时间】:2015-10-06 09:27:22
【问题描述】:

使用 Play 框架。

控制器

@BodyParser.Of(BodyParser.Json.class)
public static Result getResponseJson(Long id){
    List<DataField> entities = new Model.Finder<>(Long.class, DataField.class)
      .where("response_id = " + id).findList();
    Response response = new Response(entities, id);
    return ok(toJson(response));
}

Response 实体是:

public class Response {
  private Long uuid;
  private Map<TableField, String> map = new HashMap<>();
  ...constructors, getters and setters...
}

我用 POSTMAN 检查响应。在“原始”标签上,我得到了:

{"uuid":3942015886343226874,"map":{"Work":"Contract","locale":"Mogilev"}}

在“漂亮”标签上:

{
  "uuid": 3942015886343227000,
  "map": {
    "Work": "Contract",
    "locale": "Mogilev"
  }
}

为什么 uuid 是四舍五入的?

【问题讨论】:

  • js 中的最大数字是 +/- 9007199254740992。JS 只允许数字中的 16 位有效数字。
  • 我看到的唯一解决方案是在java中使用uuid作为String,这样会像字符串一样显示和操作,所以值不会改变。但无论如何,在其他函数中,JS 可以将其定位为数字,因此将其四舍五入...

标签: javascript java json long-integer postman


【解决方案1】:

与 Playframework 无关,是浏览器问题。在浏览器中打开开发者控制台并尝试一下 -

var c = 3942015886343226874;
console.log(c);

这将打印 - 3942015886343227000

由于 JavaScript 中的数量限制。

UUID 最好使用 String。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2017-10-28
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多