【问题标题】:Spring MVC @NumberFormat Percent with DecimalsSpring MVC @NumberFormat 带小数的百分比
【发布时间】: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


    【解决方案1】:

    尝试使用适当的模式向@NumberFormat 添加属性pattern

    来自http://docs.spring.io/autorepo/docs/spring/4.0.9.RELEASE/javadoc-api/org/springframework/format/annotation/NumberFormat.html

    对于自定义格式,将 pattern() 属性设置为数字 模式,例如#、###.##。

    每个属性都是互斥的,所以每个属性只能设置一个 注释实例(格式化最方便的一个实例) 需要)。指定模式属性时,优先 在样式属性上。当没有指定注解属性时, 应用的默认格式是基于样式的,样式为 NumberFormat.Style.NUMBER。

    【讨论】:

    • 这不起作用,因为您还必须将属性值乘以 100 才能将 0.12675 表示为 12.675%。 Java 提供了NumberFormat.getPercentInstance() 可以做到这一点,并包括十进制精度设置,但@NumberFormat 不包括可以操作这些设置的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2011-06-10
    • 2010-12-19
    相关资源
    最近更新 更多