An addition operation in Javascript

Recently, I dipped my toes into the world of Javascript. However, I found myself puzzled by the script and its corresponding HTML output provided below.

Script:

<h1>JavaScript Variables</h1>

<p id="demo"></p>

<script>
var x = 3.14;
document.getElementById("demo").innerHTML = x + 1;
</script>

</body>
</html>

Output:

JavaScript Variables

4.140000000000001

I can't help but question why the result displays as 4.140000000000001 rather than a neater 4.14? Moreover, when experimenting with adding different values to x such as x + 2, x + 3, or x + 4, the output remains similarly inaccurate. Strangely enough, it only seems to work correctly when x is paired with numbers like 10. Any insight on this matter would be greatly appreciated.

Answer №1

Computers do not process real numbers in the same way humans do, and neither method is considered entirely "correct." This is mainly due to the fact that some numbers have infinite decimal expansions that we simply don't have the time or resources to handle. For example, when we try to calculate 1/3, we get the repeating decimal 0.3333... We typically accept this as accurate even though it's technically an approximation.

Computer hardware operates on a base 2 system rather than our familiar base 10 calculations. In base 2, the infinite expansions look quite different. For instance, the fraction 1/10 in base 10 becomes 0.000110001100011... in base 2.

Both systems introduce inaccuracies because of the necessity to truncate infinitely repeating decimals. However, these inaccuracies manifest differently. Computers using base 2 can mitigate this by storing numerous fractional digits.

The key point here is that discrepancies in computed results are inevitable and should be anticipated.

If your specific application cannot tolerate these discrepancies (like certain financial programs), there are software solutions that emulate base 10 arithmetic. One such package is:https://github.com/MikeMcl/bignumber.js/

Answer №2

This particular issue arises with the number 3.14, which represents the value of PI (defined in the JavaScript MATH library with a precision of 15 digits after the decimal point). For more information on this, refer to: http://www.w3schools.com/jsref/jsref_pi.asp

To customize the number of digits displayed after the decimal point, you can utilize the toFixed() function.

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

In Internet Explorer 8, experiment with creating a unique event in plain JavaScript and then capturing it using jQuery

Currently, I am facing an issue with IE8 regarding the execution order of scripts. There is a piece of code that needs to run before JQuery is loaded so I can fire a custom event. This event will be detected later by another section of code once JQuery ha ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

Tips for updating the minimum value to the current page when the button is pressed on the input range

When I press the next button on the current page, I want to update the value in a certain way. https://i.stack.imgur.com/XEiMa.jpg I have written the following code but it is not working as expected: el.delegate(".nextbtn", "click", f ...

When attempting to establish a socket connection to a node server from an HTTPS protocol, a mixed

I have recently enhanced my website by adding a nodejs+socket.io based conversation server to it. This server is hosted on a separate AWS instance while the main website runs on HTTPS. However, I encountered an issue when trying to establish a socket conn ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

Using Angular 2 to access information from the OpenWeather API

Trying to integrate weather data from an openweather API has presented a challenge. The object received contains an array of 40 objects representing the weather forecast for the next 5 days with a 3-hour interval. The issue lies in displaying this 5-day fo ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Utilizing the Squared² Symbol in the Jscript File Path for Execution

I am encountering an issue with launching applications on a corporate portal that are tied to a specific business group. The problem arises when trying to access a file path that includes a ² character. This software is widely used on over 3000 computers ...

Refreshing Angular Services: A Guide to Resetting Factories

My angular factory is quite intricate and structured like this: app.factory("mainFcty", function(){ return { a:"", b:"", c:"" } }); When users progress through the app and complete actions such as booking a service, they f ...

What role does NPM play in the deployment of a Node.js App with AWS Beanstalk?

I'm interested in the workflow of an AWS Beanstalk deployment, particularly regarding the installation of packages. I assume that npm is used during the process to install packages on the server(s). However, I am curious to know if AWS Beanstalk utili ...

Tips for creating basic Jasmine and Karma tests for an Angular application to add an object to an array of objects

I have developed a basic Angular project for managing employee data and I'm looking to test the addProduct function. Can someone guide me on how to write a test case for this scenario? I am not using a service, just a simple push operation. Any assist ...

When starting a new project with Angular 7, the option to set up routing is automatically included without asking for confirmation

After switching from Angular 6 to version 7, I encountered an issue while creating a new project in CLI using ng new [app-name]. It simply starts without giving me the option to include routing or styling in my project. Just a heads up, I am currently run ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

Dealing with form errors - Using Node.js and Express Framework

Is there a way to handle errors that occur when dealing with null form inputs or unavailable cities from the weather api service? Sometimes, when an empty query or a misspelled city is inputted, the server returns errors and halts operation. app.get("/", ...

The MUI Slider Component is causing the entire page to go blank

I have implemented the Range Slider component: import React from 'react'; import Box from '@mui/material/Box'; import Slider from '@mui/material/Slider'; function valuetext(value) { return `${value}°C`; } export default f ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Limit input to numbers only in Semantic UI React Form Field

I've developed a custom CurrencyInput React component for users to input numeric values. I set the input type to "number", but unfortunately, this only seems to function properly in Chrome (as Firefox still allows non-numeric entries). Here is the co ...

Using React to Calculate the Total Value of Child Components within the Parent Component

In this scenario, the parent component has access to the values of the child components but struggles to calculate the sum correctly. Instead of displaying the accurate total, it shows 0. https://i.sstatic.net/1etAx.png The expected behavior is for the To ...

Nashorn poses a security threat due to its ClassFilter vulnerability

Encountering some troubles with Nashorn and came across a concerning security vulnerability highlighted here: It appears that someone can easily execute code using this command: this.engine.factory.scriptEngine.eval('java.lang.Runtime.getRuntime().ex ...