İ can not handle BigDecimal initialization properly , i have an entity which has a BigDecimal field like this:
@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.
...
}
And in frontend i use thymeleaf, in html form (which adds and updates new menu item) i have this input for Big Decimal value:
<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>
And for restrict the user to enter more than 2 digit precision on price value, i have a js code like this:
$('#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;
}
});
The question is : when user enters 10.25 value in the form , thymeleaf renders it like 10.2499998.. . Even other rest endpoints returns this entity with value in json like 10.249999. But when i looked at my database (postgresql and offcourse i use jpa) this value seems just fine which is 10.25. So i know when initializing new BigDecimal value the constructor must be like new BigDecimal("10.25") with string in parameter.But all i have is the default getters and setters and my controller is simple post controller for entity saving like this:
@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";
}
The problem 2 is : I tried to change BigDecimal with Double value and after that, the input form takes value as we suggest and i see that value everywhere correctly.But if i write more digit after comma , the js function blocks me to write more than 2 digit but real value again becomes 10.2499999.. .
It must be something with spring's strategy of taking values from thymeleaf form, and than initialize those values into entity , but i never do that manually neighter couldn't debug it.
So ı don't know the problem is if my javascript function or my input form or the variable type.Please help.
Any help will be appreciated.
I found the problem and writing here if anyone encounter a problem like this. My Problem was not in localhost , but occured on heroku.So i realized that in heroku postgresql db my BigDecimal columns did not updated and in localhost they were changing whenever i re-run because of jdbc table creation strategy choice. I made the entity attribute Double and changed remote db columns to double precision than problem solved.