Validating numbers in both Javascript and Rails

Update:

Upon further examination, it appears that when the numbers are printed out, they are identical and only display two decimal places. Additionally, in my database, these values are stored as decimal type with precision 8 and scale 2.

Within my Rails application, I have a model called "pieces" which contains two fields: artist_cut and total_price. The edit form for each piece includes javascript that calculates the total_price based on the artist_cut input. To prevent users from editing the artist_cut field, I made it readonly.

However, readonly fields can be manipulated easily, so I implemented validation to ensure that the total_price matches the expected value. If not, an error is triggered.

The validation functions correctly for all artist_cuts except those falling between 3892 and 3898. In these cases, the comparison between the calculated javascript value and the Ruby value seems incorrect. How can I resolve this issue?

_form.html.erb

<div class="form-group">
  <%= f.label :artist_cut %><br>
  <%= f.text_field :artist_cut, class: "form-control", id: "artist_cut" %>
 </div>

<div class="form-group">
  <%= f.label :total_price %><br>
  <%= f.text_field :total_price, class: "form-control", id: "total_price", readonly: true %>
</div>

<script>
    $(document).on("change", "#artist_cut", function() {
      var artist_cut = $("#artist_cut").val() || 0;
      $("#total_price").val(Math.ceil((((artist_cut*2.19)+0.3)/(1-0.029))*100)/100);
    });
</script>

piece.rb

validates :artist_cut, presence: true, format: { with: /\A\d+(?:\.\d{0,2})?\z/ }, numericality: { greater_than: 0.5, less_than: 443378.86 }
validates :total_price, presence: true, format: { with: /\A\d+(?:\.\d{0,2})?\z/ }, numericality: true
validate :total_price_validation


def total_price_validation
  return if self.total_price == ((((self.artist_cut*2.19)+0.3)/(1-0.029))*100).ceil/100.0
  errors.add(:total_price, "cannot be changed")
end

Thank you

Answer №1

It's important to note that when performing floating-point comparisons, small rounding errors may occur due to the limitations of computer representations for rational numbers. To avoid this issue, it is recommended to compare the absolute difference between the expected and actual values instead of directly comparing them.

Answer №2

Perhaps adjusting both values to two decimal places could help resolve the slight discrepancy in floating point calculations, as pointed out by csander.

Math.round(Math.ceil((((artist_cut*2.19)+0.3)/(1-0.029))*100)/100, 2)


(((((self.artist_cut*2.19)+0.3)/(1-0.029))*100).ceil/100.0).round(2)

Answer №3

It has been pointed out by others that the issue lies in using floating point comparisons, which may not be suitable for your requirements. To resolve this, consider changing the artist_cut column to a Decimal type (refer to the documentation of your specific database) and substituting float values in your code with BigDecimal.

def total_price_validation
  return if self.total_price == ((((self.artist_cut * "2.19".to_d)+"0.3".to_d)/(1 - "0.029".to_d)) * 100).ceil / 100

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

"Exploring the World of ASP.NET VB: A Beginner's Guide to

Attempting to call a web service using JS from an ASP.NET website (VB) client side. Although familiar with web services, setting one up is new territory for me. Looking to implement async updates and queries. Any assistance, examples, or best practices wou ...

Can a <Link> be customized with a specific condition?

On the webpage, there is a list of elements retrieved from a database. When clicking on the last displayed element, I want to link to '/upload' if it shows "Carica Referto", or link to '/consensi/{this.$state.item.hash_consenso}' if it ...

Having trouble with a jQuery selector that is supposed to target an element with both an id and

A scenario where a specific event-handling function is in place: jQuery(document).on('click', '#button .submitb', function(e){alert();}); Despite having jQuery included in the HTML document, clicking on <div id="button" class="subm ...

Issues with Javascript code syntax

I have encountered an issue while creating a new literal control from code behind. I am able to add standard HTML into it successfully, however, when I try to insert <%= SomeDiv.ClientID %> into the literal control, it simply prints exactly what is i ...

Substitutions not functional when using SendGrid in conjunction with Firebase functions

I'm encountering difficulties when trying to include substitutions data in emails sent from Sendgrid using Firebase Cloud Functions. Here's my function exports.firestoreEmail = functions.firestore .document('users/{id}') .onCreate(s ...

React - Struggling to render an image received as a prop within a React component

Just starting out with React. I'm trying to figure out how to properly display an image from the props of my CheckoutProduct component inside an image HTML tag. Image displaying the Product item but failing to do so. Here's the code snippet: i ...

Incorporating visuals into dynamic circles that are in motion and interacting

I have a collection of bouncing balls that are colliding with each other within a confined space. Currently, the balls are just simple green circles. However, I would like to replace them with images. How can I accomplish this? Here is the render functio ...

These specific resources don't have a cache expiration set. Wondering how to properly set a cache expiration for a JavaScript file

I am working on a web application that utilizes external JavaScript files. Upon running Google's page speed tool, I realized that several resources are missing cache expiration settings, including images and CSS files. Can you provide examples of how ...

Tips for preventing the need to open numerous chrome windows when running multiple URLs with Selenium WebDriverJS

Is there a way to prevent multiple instances of the browser from opening when attempting to parse multiple URLs? I would like to have just one browser open and running all the URLs within it. Any advice or suggestions would be greatly appreciated! I' ...

Iterating over a JSON object with an embedded index in Angular using ng-repeat

Here is the structure of a JSON object: { "0": { "Order_Id": "100000001", "prodct_Status": "Pending", "Price": "8.0000", "date_created": "Jun 4, 2014 7:55:42 AM", "Shipping_Address": "vbccv", "Region": ...

Enhancing jQuery Rating Plugin

Currently, I am working on customizing the jQuery Bar Rating System Plugin. You can view an example of the plugin by visiting this link: . The rating system on my end will resemble Example D. Rather than having the plugin based on user input, my goal is to ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

issues with the game loop functionality

Help needed: How can I eliminate the delay in moving my player? I tried implementing a game loop after reading some online articles like "Is it possible to make JQuery keydown respond faster?" However, I keep encountering an error in my console stating Unc ...

When generating a fresh event and attempting to link the event ID to its creator, unexpected obstacles emerged

I am currently working on an application that revolves around events. One of the key features requires users to be logged in to create events, and upon creation, I need to update the user's events array with the event ID. However, I have encountered a ...

Guide to using the ng-click function in Angular to set focus on the input in the last row of a table

I am in the process of developing a task management application and I am looking to implement a specific feature: Upon clicking 'Add Task', a new row is automatically added to the table (this part has been completed) and the input field within ...

Disabling functionality is not working properly when multiple expressions are added

One specific scenario involves using a radio button for selecting options and requiring users to confirm their selection using the JavaScript confirm method before enabling the next button. Take a look at the following code: HTML <body ng-controller ...

What is the best way to utilize mouseenter and mouseleave events concurrently?

I need some assistance with my website's star rating feature. When a user hovers over the stars, a popover should appear, and when they move their mouse away, the popover should disappear. Currently, I am using jQuery to achieve this functionality: $( ...

Alter the hue within Google Chart

I'm working on customizing a Google Bar Chart with Material design and running into an issue with changing the background color. I've tried using backgroundColor and fill identifiers in the options, but the inner area of the chart where the data ...

Using the spread syntax to copy properties of a React component may result in an error

I've been experimenting with the spread syntax in React and I've encountered an issue. When trying to destructure props using the spread operator, I keep getting an error message: const { className, children, ...otherprops } = this.props; Has a ...

Configuring Multer destination dynamically using FormData values in Node.js

I have a scenario where I need to send a file along with some data values using an XMLHttpRequest (xhr) to a Node.js server running Express. To handle multipart data, I am utilizing Multer as bodyParser does not work in this case. router.post("/submit", f ...