When a decimal of 0.02 is added to a number in javascript, it may lead to

I am attempting to create an array of numbers ranging from a specific minimum value to a certain maximum value with a specified decimal interval, such as 0.02. For instance, the sequence would be like: 1.00, 1.02, 1.04, 1.06

The issue arises when the code encounters the number 1.14:

function getValues(minValue, maxValue, increment) {
  var values = [];

  for (var i = minValue; i <= maxValue; i += increment) {
    values.push(i);
  }

  return values;
}

var values = getValues(1.0, 1.4, 0.02);

At this stage, the values array appears as:

[
    1, 
    1.02, 
    ...
    1.12, 
    1.1400000000000001, 
    1.1600000000000001
    ...
]

What is causing this discrepancy and what steps can I take to rectify it?

Answer №1

According to the article What Every Programmer Should Know About Floating-Point Arithmetic:

Computers internally use a binary floating-point format that struggles with accurately representing numbers like 0.1, 0.2, or 0.3.

By the time your code is compiled or interpreted, the value of "0.1" has already been rounded to the closest number in that format, leading to minor rounding errors even before any calculation takes place.

When it comes to JavaScript specifically:

JavaScript numbers are essentially floating points as outlined by IEEE-754 standards. Due to limitations in base-2 number representation and the constraints of finite machines, we encounter a format fraught with rounding errors. This article delves into the reasons behind these errors and emphasizes using reliable libraries for handling numerical computations instead of creating one from scratch.

I have found success utilizing this port of BigDecimal and the more streamlined, efficient big.js library.

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

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

Is your event listener failing to activate?

I have been working on a project where I gather array elements from user input and try to display them in an HTML table. Unfortunately, the event listener seems to not be triggering, and I can't figure out why. Here is the relevant HTML code: ...

What is the method for retrieving a variable from a Q Node promise?

I am currently developing a learning game utilizing Angular, Express, MongoDB, and Node. As part of my learning process, I have been exploring the use of promises to manage asynchronous operations effectively. One particular challenge I am facing involves ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

Understanding how to activate a React navbar button is essential for creating a seamless user

How can I make my sidebar button change color when I navigate to the page it links to? ...

Looking for guidance on building a real-time React application with automatic data fetching linked to a nodejs backend

I have a simple question, I have developed an app that retrieves data from a backend server, Now, the app needs to be accessed and edited by multiple users simultaneously while ensuring that all changes made to the list are reflected in real-time for ever ...

issue with the submit button due to non-functional base64 encoded image

After successfully converting multiple file images to base64 format, I encountered an issue when trying to submit the values. When a user selects multiple images and clicks the submit button, the converted base64 values are returned as undefined. How can t ...

Implementing AJAX to seamlessly add comments in real time!

I have set up a commenting system on my website using two PHP files: index.php and insert.php. The index.php file contains a form where users can input their comments, which are then displayed on the page through an echo statement after being stored in the ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

JavaScript/jQuery boolean data type

In my current coding project, I am dealing with a scenario where the user has the option to download either a specific "Slice" of a pie chart or the entire chart. When a user clicks on a slice, it sends a variable named source to indicate which slice was ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Update the color of the div when all checkboxes in the hidden form are selected

Seeking help for multiple issues I'm facing with my code. Here is the link to the code. HTML for Upper Table: <div class="block"> <table> <tr> <th>Nr.</th> <th style="width: 200px">Task</th& ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Using C# Razor Pages to send checkbox values via AJAX requests

In my model class, I have the following: public class DataModel { public bool Display { get; set; } } After deserializing a FormData object to a JSON object, I am posting the value from a checkbox like this: this.FormToJSON = form => { const ...

What could be causing the Babel installation to fail within Electron? Is Babel necessary for my project or can it be avoided?

Having trouble using the npm package https://www.npmjs.com/package/swipe-detect and encountering the following error message: export default function(target, callback, threshold=150) { ^^^^^^ SyntaxError: Unexpected token export at Module._compile (i ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

Toggle visibility with jQuery's Show & Hide feature

Currently, I am working with some divs that need to be hidden (with the class .hideable) and others that need to be shown (with the class .toggleable). I have made progress in getting everything to work as desired. However, I am facing a challenge - once t ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...