从JSON中获取的BigDecimal失去了精度。

huangapple go评论75阅读模式
英文:

BigDecimal from json loses precision

问题

网络调用显示后端正在发送以下内容:

"uom" : "EA",
"qty" : 1.123456789012345678

但当它到达前端并使用console.log时:

{ 
  qty: 1.1234567890123457, 
  uom: "EA"
}

为什么JavaScript会丢失最后一位数字或截断这个数字?

这个数字在Java中使用BigDecimal表示。前端使用AngularJs框架,向后端发起GET调用以请求JSON。

英文:

The network call shows that the backend is sending this:

"uom" : "EA",
"qty" : 1.123456789012345678

but when it reaches the frontend, using console.log:

{ 
  qty: 1.1234567890123457, 
  uom: "EA"
}

why is the javascript losing the last digit or truncating the number?

The number is represented using a BigDecimal in java. The frontend use AngularJs framework, makes a GET call to the backend requesting a JSON.

答案1

得分: 2

JavaScript浮点数保留64位精度,类似于Java中的double。如果您需要在Java中使用BigDecimal来扩展超过这一精度级别,那么在JavaScript中需要采取类似的方法来扩展其类似的边界。NPM包js-big-decimal可能是您最好的选择,并且您可以将这些值以JSON字符串的形式传输,以防止JSON.parse将其解释为数字。

英文:

Javascript floating point numbers hold 64 bits of precision, similar to a double in Java. If you have to use BigDecimal in Java to extend beyond that level of precision, you'll need to do something similar in Javascript to extend beyond its similar boundary. The NPM package js-big-decimal is probably your best bet and you can transfer the values as strings in JSON to prevent JSON.parse from interpreting them as Number.

答案2

得分: 0

感谢您的帮助。我发现将以下内容添加到Java领域对象可以解决这个问题:

@JsonSerialize(using = ToStringSerializer.class)
public getQty(){
   return this.qty;
}
英文:

Thanks for the help. I found that adding

@JsonSerialize(using = ToStringSerializer.class)
public getQty(){
   return this.qty;
}

to the java domain object solves the issue.

huangapple
  • 本文由 发表于 2023年2月16日 02:49:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定