bigdecimal:零作为最后十进制的问题
我有一个春季启动应用程序,该应用程序消耗REST API,可提供一些小数点值 例如:
"Amount": {
"Amount": 160.10,
"Currency": "EUR"
}
我将其映射到bigdecimal
,这给了我问题。我需要最后一个小数,即使是零,因为我需要没有小数的金额,即使用bigdecimal.unscaledvalue()
用于显示的数据,我期望x的输出。 getAmount()。unscaledvalue()
为“ 16010”
,但是由于该值内部表示为160.1
(剥离了不合时宜的0),我得到<<代码>“ 1601” 是10倍折扣,当某些代码进一步划分除以10时。
该值可以具有0、2或3个小数位置(取决于货币)。
我的第一个想法是使用setScale()
方法,但这给我带来了任何运气。
Java 11代码解析JSON:
restTemplate
.exchange(request, new ParameterizedTypeReference<List<NotificationMessage>>() {})
.getBody()
型号:
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import lombok.Data;
@Data
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class TransactionAmount {
// @JsonRawValue //my test to force it
private BigDecimal amount;
private String currency;
}
有没有办法强迫Spring Boot保留不重要的小数?
(将API修改为使用字符串不是一个选项)
I have a Spring Boot application consuming a rest api delivering some decimal values
for example:
"Amount": {
"Amount": 160.10,
"Currency": "EUR"
}
I map this to BigDecimal
which is giving me issues. I need the last decimal, even if it is zero, because I need the amount with no decimals, ie using BigDecimal.unscaledValue()
For the shown data I would expect the output of x.getAmount().unscaledValue()
to be "16010"
but since the value is internally represented as 160.1
(non-significant 0 is stripped) I get "1601"
which is a factor of 10 off, when some code further down the line divides by 10.
The value can have either 0, 2 or 3 decimal places (depending on the currency).
My first thought was to use the setScale()
method, but that brought me no luck.
Java 11 code to parse json:
restTemplate
.exchange(request, new ParameterizedTypeReference<List<NotificationMessage>>() {})
.getBody()
model:
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import lombok.Data;
@Data
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class TransactionAmount {
// @JsonRawValue //my test to force it
private BigDecimal amount;
private String currency;
}
Is there a way I can force Spring Boot to preserve the non-significant decimals?
(modifying the API to use strings instead is not an option)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案仅仅是为了引入自定义
Jackson
mapper
将值解析为string
而不是float
:Solution was simply to introduce a custom
Jackson
Mapper
which parses the value asString
instead offloat
: