Discrepancy in Rounding Methods: Android App vs. JavaScript Implementation

When working with numbers, I encountered a discrepancy in the results obtained from calculating and rounding. The value for today is 336887, and for yesterday it is 336582. I faced a similar issue with a different field, but after updating the Java code, the difference disappeared.

Snippet of Javascript Code:

    document.getElementById("txt1").value = ((today - yesterday) / 10000).toFixed(3);

Snippet of Android Code:

    public Double RoundDouble(Double num, Integer places)
    {
        Double temp = Math.pow(10.0, places);

        num = num * temp;
        Math.round(num);
        num = num / temp;

        return num;
    }

    Double total = RoundDouble((today - yesterday) / 10000,3);
    txt1.setText(df.format(total ));

The calculated results differ where the Javascript code returns .031, and the Android code returns .030. The calculation before rounding gives .0305. The reason behind this discrepancy is unclear, especially when another field had no issue rounding .0295 to .030 accurately.

Answer №1

The expression ((336887 - 336582) / 10000) cannot be accurately represented as an IEEE-754 double precision number. By using

((336887 - 336582) / 10000).toFixed(20)
, you will see the result as 0.03049999999999999933. The discrepancy between versions of Android could stem from how the return value of Math.round(num) is handled - it might be ignored. Consider updating the line to num = Math.round(num); for better handling. Furthermore, it is worth noting that the rounding mode in Android can be modified. In ECMAScript, the default rounding mode is nearest-to-even, which equates to HALF_EVEN in Android.

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

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Utilizing JavaScript to dynamically set a CSS file from an API in AngularJS

I am currently facing an issue with integrating a CSS file returned by an API into my entire website. Since the URL of the CSS file keeps changing, hard coding the URL is not feasible. While I have successfully implemented this on 'view1', my goa ...

Utilize web workers for efficient processing of a limited number of files simultaneously in JavaScript

Utilizing the web worker concept for file uploads has resulted in creating a web worker for each selected file. The idea now is to optimize this process by creating 5 web worker threads to handle the first batch of five files, terminating them afterwards b ...

What is the best way to showcase an ajax response on an HTML webpage?

Apologies for the length of the code, but I'm looking to condense it while maintaining the same functionality. Is there an alternative approach or method that could achieve the same results? I receive data from PHP, which is then passed to JavaScript ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Encountering issues with the setValue function in Nightwatch

Currently, I am in the process of setting up a new Nightwatch project to automate a basic Google search page. The assertion for searchbox present on page is successful, but I am facing difficulties performing any mouse or keyboard actions on the elements ( ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Issue with HTTP POST Headers in XmlHttpRequest

I am currently attempting to pass a string using the XmlHttp method. Let me provide you with the code for better understanding: HTML <div id="greetings"> You are voting out <b style="color: #00b0de;" id=roadiename></b>. Care to explain ...

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

Generating a new array in NodeJs from data retrieved by querying MySQL

In my NodeJs project, I am trying to generate a new array from the results of a MySQL query. Here is the current result: [ { "availabilityId": 1, "dayName": 1, "fromTime": "05:30:00", "toTime": "10:00:00" }, { ...

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

What is the best way to include query parameters in form data within a Rails link_to instead of tacking them onto the URL?

I am facing an issue with my page that displays transaction search results. I have a search filter based on the "Token" column and when clicked, the search criteria should be set, and the search params should be passed as form-data in a POST method. Howeve ...

How can I switch to another screen from the menu located within my Parent Component?

I've been working on adding a customized navigation menu to my react-native app, but I'm currently facing the challenge of not being able to navigate to the corresponding screens of the selected menu items. I tried using this.props.navigation.nav ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Feeling trapped during the process of setting up a intricate jQuery Image Slider

I've hit a roadblock while trying to make changes to the slider located at THIS URL. In the current setup, each thumbnail corresponds to one main display image. Clicking on a thumbnail displays a single image and then proceeds to slide to the next th ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...

javascript selecting window location strings

Hey there, http://localhost/estamo/asset.php?aname=VklQIFBsYXph&di=Ng== I have this URL and I want to retrieve it using Javascript: var locat = window.location.href; $.get("enviaramigo.php?email="+$("#email").val()+"&url="+locat, function(h ...