Converting integers to decimals in a Ruby on Rails form input field

I've recently taken over a Ruby on Rails app that makes use of the administrate gem for its admin dashboard.

Within this project, there is a product model where each product has an attribute for wholesale case price. This attribute, named wholesale_case_price_cents, stores values as integers. All prices in the application are managed as integers.

The problem I'm facing is that certain numbers entered into the admin dashboard input field end up converting to decimals. For example, entering the integer 3780 results in the value changing automatically to 3779.9999999999995 before submission. You can refer to the screenshot here: https://i.sstatic.net/DLuqd.png

It's important to note that this automatic conversion only occurs with specific numbers, not all. Check out another example in this screenshot: https://i.sstatic.net/m1qc2.png

The app also incorporates the administrate-field-money gem, money-rails gem, and monetize gem. My suspicion is that the issue lies with the administrate-field-money gem, although I haven't been able to identify a solution other than removing the gem entirely. Has anyone else faced this same challenge?

Answer №1

Seems like there is an issue with the JavaScript code in administrate-field-money on this line

return $el.maskMoney('unmasked')[0] * 100;

When the value is 37.80:

37.80 × 100 = 3779.9999999999995

This illustrates how floating-point numbers work in various languages

There's a different branch available as well, where

Math.round($el.maskMoney('unmasked')[0] * 100)

This will result in 3780

You might need to update the gem version, or specify a specific branch on GitHub in your Gemfile, or find another way to address the issue in this JavaScript file

Answer №2

One of the reasons for this discrepancy is due to how floating-point math operates in the JavaScript code that comes with your chosen library.

An effective solution is to carefully filter the input parameters in your Ruby code. It's a known fact that when using floating-point math, the resulting values might be slightly off from the actual integers they represent. To address this issue, you can implement the following adjustment within your controllers:

price = params[:product][:wholesale_case_price_cents].round()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...

Tips for utilizing useQuery when props change using Apollo:

I am currently facing a challenge with my BooksList component where I need to pass props down to the BooksDetails component only when a title is clicked. I am trying to figure out how to utilize an Apollo hook to query only on prop changes. I have been ex ...

"Implementing the use of 'if' statements to increment the score when matching an element in

Hey there, I'm still pretty new to JavaScript and finding W3 Schools a bit overwhelming. Could someone please guide me on how to increment the score by 1 if getanswer1 is equal to answer[0]? I've watched countless tutorials on creating quizzes, ...

Error: The term "User" has not been previously defined

I encountered an issue while attempting to authenticate via vkontakte (vk.com) using passport-vkontakte. Error: A ReferenceError: User is not defined Below is the content of my auth.js file. var express = require('express'); var passport ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

How can we calculate mesh positions and create a new Point3D object with specified coordinates (x, y,

private void BuildVertices(double x, double y, double len) { if (len > 0.002) { mesh.Positions.Add(new Point3D(x, y + len, -len)); mesh.Positions.Add(new Point3D(x - len, y - len, -len)); mesh.Positions.Add(new Point3D(x + len, y - len, -l ...

Utilizing the v-for directive to loop through JSON data with unique IDs and linking them to Input components in PrimeVue

In my database, I have a collection of products with a column named attributes that stores property/value pairs in JSON format. Each product can have unique attributes. For instance, one product's attributes could be: #product1 attributes { color: & ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

When attempting to browse for image files, Postman fails to display images

While trying to upload image files through Postman, I encountered an issue where the browser did not display any image files. It's important to note that I am using Ubuntu as my operating system. https://i.sstatic.net/1D3ro.png When I clicked on "se ...

Connecting one property of a JavaScript object to another property within the same JavaScript object

I am working with a JavaScript Object and I want to use the map() function to match the Id with another id in the same JavaScript Object. Here is the schema for my JavaScript Object: var items = [ { BossId: "03", DateOfBirth: "1966-09-27T00:00:0 ...

After making a request with HttpClient, the response can either be an empty body or a body

Encountering issues with HttpClient while trying to post data, I am faced with two distinct errors: When booking is treated as an object, the error message reads: Backend returned code 400, body was: [object Object]. Converting booking to JSON format by ...

Altering CSS attribute values using a random number generator

Is there a way to randomly change the animation-duration attribute in the following CSS code? I want it to range from 0 to 1. @keyframes blink { 50% { border-color: #ff0000; } } p{ animation-name: blink ; animation-duration: 0.1s ; animatio ...

Exploring the contents of this JSON array

I'm trying to fetch data from this link: <script type="text/javascript"> $.getJSON('http://api01.notaion.com/?item&id=120001462', function(data) { }); </script> I am uncertain whether I need to use a callback=?, a ...

Fetching information from server proves to be sluggish within AngularJS application

In the process of developing a web application, I am faced with the task of sending numerous $http requests to the server. My front-end is built using AngularJS while the back-end utilizes ExpressJS. The $http requests are currently being made as shown in ...

Can you create reusable components in Wordpress that are encapsulated?

In my quest to explore innovative approaches to Wordpress theme development, I have stumbled upon a variety of options such as the "Roots Sage" starter theme, the "Themosis Framework," and "Flynt." While these solutions address intriguing problems, they do ...

Is it possible to access values stored in an AngularJS service without explicitly sending them back?

Any insights on how this system operates would be greatly valued. My service stores session-specific variables, like table sorting preferences, and other related data. The code appears to be functioning correctly. However, my query pertains to retrieving ...

JQuery does not immediately update the input value

I'm working on a jQuery placeholder that mimics the behavior of default placeholders in Chrome and Firefox for browsers that don't support it. However, I'm facing an issue where the placeholder div's HTML doesn't change as quickly ...

Encountering an error in Javascript: "Uncaught SyntaxError: import statement cannot be used outside a module". Successfully resolved the issue

Delving deep into the details, my current objective is to pull in code from a JS file named GLTFLoader for Three.js. The ultimate aim is to parse a .GLB file and display a Teapot. HTML: <!DOCTYPE html> <html> <head> <meta charset= ...

Requiring the specification of a particular generic Closure type

Failure to specify a generic type parameter in Closure generally does not result in an error, unlike languages such as TypeScript. In Closure, the unspecified type is treated as "unknown", often being ignored. (Although it is possible to adjust compiler fl ...

What is the best way to display PHP/SQL data within an HTML page using AJAX?

I have successfully tested the .php file directly, leading me to believe that the issue lies in how I am displaying the AJAX result. As a newcomer to AJAX, I am working on a form where users can input date ranges for searching purposes, and wish to have ...