Spring 引导和 BigDecimal 或 Double 序列化问题

Spring boot and BigDecimal or Double serialization problem


© 无法正确处理 BigDecimal 初始化,我有一个具有 BigDecimal 字段的实体,如下所示:

@Entity
public class Menu{
...
   @Digits(integer=6, fraction=2)
   private BigDecimal price;
...
public BigDecimal getPrice() {
    return price;
}

public void setPrice(BigDecimal price) {
    this.price = price;
}
...
other generated getters and setters toString etc.
...
}

并且在前端我使用 thymeleaf,以 html 形式(添加和更新新菜单项)我有这个大十​​进制值的输入:

<div class="form-group">
        <label for="price">Enter Price</label>
        <input type="number"  class="form-control" step="0.01" id="price" name="price" th:field="*{price}" placeholder="enter Price" value=" ">
</div>

并且为了限制用户在价格值上输入超过 2 位精度,我有这样的 js 代码:

$('#price').keypress(function (e) {
                var character = String.fromCharCode(e.keyCode)
                var newValue = this.value + character;
                if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
                    e.preventDefault();
                    return false;
                }
            });

问题是:当用户在表单中输入 10.25 值时,thymeleaf 将其呈现为 10.2499998..。甚至其他 rest 端点 returns 这个实体的值在 json 中,比如 10.249999。但是当我查看我的数据库(postgresql 和 offcourse 我使用 jpa 时)这个值似乎很好,是 10.25。 所以我知道在初始化新的 BigDecimal 值时,构造函数必须像 new BigDecimal("10.25") with string in parameter.But 我所拥有的只是默认的 getter 和 setter,我的控制器很简单 post 实体控制器像这样保存:

@PostMapping("/additem")
    public String addItemPost(@ModelAttribute(value="menu") @Valid Menu menu,Model model,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "addmenuitem";
        }
        this.menuService.saveMenuItem(menu);
        return "redirect:/restaurant/menu";
    }

问题 2 是: 我尝试将 BigDecimal 更改为 Double 值,之后,输入表单采用我们建议的值,我到处都看到该值 correctly.But 如果我在逗号后写更多数字,js 函数会阻止我写超过 2 位数字,但实际值再次变为 10.2499999..。
这一定与 spring 的策略有关,即从 thymeleaf 表单中获取值,然后将这些值初始化为实体,但我从来没有手动执行过,更晚无法调试它。
所以我不知道问题出在我的 javascript 函数或我的输入表单或变量 type.Please 是否有帮助。 任何帮助将不胜感激。

我发现了问题并写在这里如果有人遇到这样的问题。 我的问题不在 localhost 中,而是发生在 heroku.So 我意识到在 heroku postgresql db 中我的 BigDecimal 列没有更新并且在 localhost 中它们在我重新 运行 因为 jdbc table 创建策略选择。 我将实体属性设置为 Double 并将远程数据库列更改为双精度,而不是问题已解决。