【发布时间】:2015-06-30 15:50:43
【问题描述】:
我正在使用 Spring MVC (4.1.6.RELEASE) 和 Thymeleaf (2.1.4.RELEASE)。我的实体类有一个百分比字段存储为float。
@Entity
@Table(name="loans")
public class Loan {
private float percentage;
...
@NumberFormat(style=NumberFormat.Style.PERCENT)
@Column(name="percentage")
public float getPercentage() {
return percentage;
}
public void setPercentage(float percentage) {
this.percentage = percentage;
}
...
}
我的视图使用 Thymeleaf Spring 方言将此 bean 绑定到表单。
<form th:object="${loan}" th:action="@{/form-handler}">
<input type="text" th:field="*{percentage}" placeholder="e.g. 1.5%" />
<input type="submit" />
</form>
表单绑定在提交时可以正常工作。 “12.675%”的输入值绑定到 bean 并作为“0.12675”保存到数据库中,但是当在编辑表单中显示时,Spring 的 @NumberFormat 注释在使用 NumberFormat.Style.PERCENT 时会自动舍入到 13%。我想显示小数点,即“12.675%”。
我曾考虑在我的实体上编写一个单独的 getter(例如 getPercentFormatted),但随后 th:field="*{percentFormatted} 字段无法在我的控制器中正确绑定。我想我也可以编写一个额外的设置器,它会除以 100 并设置属性,但我不喜欢这种方法。有什么建议吗?
【问题讨论】:
标签: java spring spring-mvc number-formatting thymeleaf