I've inherited a Ruby on Rails app that uses the administrate gem for an admin dashboard.
This project includes a product model, and each product has a wholesale case price. This field is called wholesale_case_price_cents and is an integer. All prices in the app are handled as integers.
The issue I'm encountering is that some numbers, when entered into the admin dashboard input field, turn into a decimal. For instance, if I input the integer 3780, the input value automatically changes to 3779.9999999999995. See screenshot:
As you can see, the input value is changed automatically before submission. It doesn't do this for every number, only certain ones:
The app also utilizes the administrate-field-money gem, the money-rails gem, and the monetize gem. I suspect it's the administrate-field-money gem causing the issue, but can't figure out how to fix it, short of removing the gem. Anyone else encounter this issue?
CodePudding user response:
Looks like problem in the JavaScript problem of administrate-field-money
in this line
return $el.maskMoney('unmasked')[0] * 100;
And when value is 37.80:
37.80 × 100 = 3779.9999999999995
This is how floats in many languages work
There is other branch. And there
Math.round($el.maskMoney('unmasked')[0] * 100)
This will return 3780
Probably you need to bump this gem version, or specify branch on github in your Gemfile
or somehow patch this JS file
CodePudding user response:
As mentioned in other answers this is because of floating point math in the JS provided by your library.
A simple way to resolve it is to sanitize the submitted params in Ruby. You know that floating point math will produce floats that are very close to the integer they're meant to represent. Therefore, in your controllers you could do this:
price = params[:product][:wholesale_case_price_cents].round()