英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论