Issue with comparing equality to zero

function compare() {
  var value1 = parseInt(document.getElementById("box3").value);
  var value2 = parseInt(document.getElementById("box4").value);
  var display = document.getElementById("box5");
  if (value1 === 0 || value2 === 0) {
    display.value = "You have entered zero";
  } else if (value1 == value2) {
    display.value = "The numbers are the same";
  } else if (value1 % value2 == 0) {
    display.value = "The first is divisible by the second";
  } else if (value2 % value1 == 0) {
    display.value = "The second is divisible by the first";
  } else {
    display.value = "They are not divisible";
  }
}
<p> Enter two numbers and we will inform you about their divisibility</p>
<p> Enter your first number:</p> <input type="text" id="box3">
<p> Enter your second number: </p> <input type="text" id="box4">
<button id="compareValue" onclick="compare()">Compare Values</button>
<p> Output will appear here: </p> <input text="type" id="box5" disabled>

In the code above, inputting 89.09 into the first number field and 0.05 into the second number field. Clicking on compare values results in:

You have entered zero

https://i.sstatic.net/XCoNc.jpg

The question remains, why?

Answer №1

When trying to parse the value 0.05 as an integer, the result is 0:

The parseInt() function takes a string argument and returns an integer based on the specified radix (the base in mathematical numeral systems).

Source

If you are aiming to work with decimal numbers like 0.05, consider using parseFloat() instead:

var value1 = parseFloat(document.getElementById("box3").value);
var value2 = parseFloat(document.getElementById("box4").value);

An alternative approach would be to convert it into a number by either using Number() or the + prefix operator, as suggested by @pointy below:

let value1 = Number(document.getElementById('box3').value);

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

Is it possible to access a comprehensive list of all the elements that are currently available?

Is there a way to retrieve all HTML tag names that are supported by the browser for my web application? I want it to be displayed like this: console.log(getAllElements()) //[a, abbr, acronym, address, applet, area, base, ...] ...

Understanding Vue.js: Effectively communicating updates between parent and child components using scoped slots

My goal is to develop a component with two slots, where the second slot repeats based on the number of items in the first slot. I have successfully implemented this using scoped slots. However, I noticed that when the data in the first slot is updated, the ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

Securing User Profiles in Firebase

I am currently working on a coding issue that involves the security of user profiles. While it doesn't involve sensitive information like payment details or personal data, it does pertain to the ownership of a profile. Currently, I store users' ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Automated login feature in JQuery utilizing localStorage

I've been working on implementing an automatic login feature for users using the "Remember Me" functionality. Below is the code I have written, but unfortunately, it's not logging in users automatically: if (localStorage.getItem("username") != ...

"Retrieve and transfer image data from a web browser to Python's memory with the help

Is there a way to transfer images from a browser directly into Python memory without having to re-download them using urllib? The images are already loaded in the browser and have links associated with them. I want to avoid downloading them again and ins ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Enable automatic suggestion in Monaco Editor by utilizing .d.ts files created from jsdoc

I am in the process of creating a website that allows users to write JavaScript code using the Monaco editor. I have developed custom JavaScript libraries for them and want to enable auto-completion for these libraries. The custom libraries are written in ...

Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link. However, the output I receive is either undefined or completely empty. <li v-for="(category, index) in categories" :key="index"> ...

Using JSON to create bootstrap styled link buttons

My current code is functioning well with links. However, when I try to use a bootstrap button instead of a regular button, the button appears in the table but no longer directs to the link. var button = "<button class='btn btn-inf ...

Is it possible for my code in ReactJS to utilize refs due to the presence of backing instances?

When working with ReactJS components, I often piece together JSX elements to create my code. For example, take a look at the snippet below. I recently came across this page https://facebook.github.io/react/docs/more-about-refs.html which mentions that "Re ...

The current error message states that the function is undefined, indicating that the Bookshelf.js model function is not being acknowledged

I have implemented a user registration API endpoint using NodeJS, ExpressJS, and Bookshelf.js. However, I encountered an error while POSTing to the register URL related to one of the functions in the User model. Here is the code snippet from routes/index. ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

Struggling to Convert Array of MongoDB Documents from Backend into React Components

In an attempt to connect my front-end to the back-end, I am looking to retrieve all the "blog posts" stored in my MongoDB database. Currently, there is only one document available for testing purposes. The backend contains this API endpoint: app.get("/api ...