Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05.

The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues:

  1. The calculated value should be rounded to two decimal points. For example: 3284.40 instead of 3284.40000000000003
  2. The previous output should automatically clear when a new calculation is performed.

decimal

<script>
    function doMath() {
    var numOne = document.getElementById('num1').value;
    var numTwo = document.getElementById('num2').value;
    var theProduct = 0.05 * parseInt(numTwo);
    var p = document.getElementById('theProduct');
    p.innerHTML += theProduct;
    document.getElmentById('doMath').innerHTML='';
    }
</script>
    <input id="num1" type="hidden" name="num1" value="0.05" readonly><br> Value:<br>
    <input id="num2" type="text" name="num2">
    <br><input type="button" value="Convert" onclick="doMath()" />
    </div><div id="theProduct">$</div>

For an input value of 5688, the expected output is 3284.40, however the actual output includes additional decimal places (3284.40000000000003).

Upon clicking "Convert" multiple times, the expected output is 3284.40, but the actual output doesn't clear properly and results in incorrect values (284.40000000000003284.40000000000003)

Answer №1

If you want to handle decimal points, try using this method

function roundNum(num, dec = 2) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

Next, let's update the content:

document.getElementById('theProduct').innerHTML = '$';

To display the new content:

document.getElementById('theProduct').innerHTML = '$' + parseFloat(result);

Make sure 'result' contains the value from your previous calculation.

If you need to add it to the previous result:

var el = document.getElementById('theProduct');
el.innerHTML = '$' + (parseFloat(el.innerHTML) + result);

Feel free to make any adjustments and enjoy experimenting! :)

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

Create an instance using the window object in JavaScript

Having an issue when trying to instantiate a class using the window object. I have a namespace called UTIL and within it, there is a class defined as follows: var UTIL = { Classes : {}}; UTIL.Classes.ObservationVal = function(state, id, type, context, pe ...

Using selenium for testing JavaScript elements through RSpec results in failures in other segments of the RSpec test

Trying to implement Stripe into my web application has brought me to a frustrating roadblock. Every attempt to test the "Pay with Card" button seems to be thwarted by an ElementNotFound error thrown by rspec. Research revealed that the root cause of this ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

Is it necessary to have nodejs, or can I just depend on Nginx alone?

I am currently in the midst of a discussion with my colleagues regarding whether or not to incorporate node.js into our application. We have decided to utilize angular.js for the front-end and communicate with the app server through a REST api. The app ...

Angular 2: Navigating through submenu items

I have a question about how to route submenu elements in Angular 2. The structure of my project is as follows: -app ---login ---registration ---mainApp (this is the main part of the app, with a static menu and links) -----subMenu1 (link to some con ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

Troubleshooting Cloud Functions: Fixing functions.logger.log not Functioning

Whenever a user updates the chat/{id} documents, this function is triggered. const functions = require("firebase-functions"); exports.onChangedChat = functions.firestore .document('chat/{id}') .onWrite((change, context) => { fun ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

Tips for keeping JavaScript created checkboxes saved and accessible

Utilizing the "ajax" function within the script enables communication with the server by sending post or delete messages. The javascript code that includes ajax is responsible for dynamically adding checkboxes to the page. How can we ensure that the create ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

Refresh the Vue page only once after it is mounted

Users should only experience the page refreshing once upon visiting. However, if I add location.reload() within the mounted() function, it causes an infinite loop of page reloads. ...

The compatibility between Node JS and Vue JS front-end seems to be glitchy and

I am currently developing a Node JS backend application and Vue JS front-end. In order to authenticate users, I need to implement sessions in the API. For my backend server, I am using the following components: express (4.18.2) express-session (1.17.3) c ...

Tips for retrieving specific information from Wikipedia using AJAX

Is there a way to retrieve the information consistently displayed in the right box during searches using AJAX? I've tried using the Wikipedia API, but haven't been able to find the specific information I need. ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

What steps are involved in integrating Element Plus with Nuxt 3?

Seeking assistance with installing Element Plus in Nuxt 3. I followed the instructions from the official Element Plus documentation, but despite adding unplugin-vue-components, unplugin-auto-import, and adjusting webpack settings in the nuxt config file, ...

Having trouble finding the element within the form tag even after attempting to use .switchTo().defaultContent()

My HTML is structured like this: <section> <div> <form> <div>Username field</div> <div>Password field</div> <div> <div>.. <div>.. <iframe& ...

Creating an 8-bit grayscale JPEG image using HTML5 and encoding it from a canvas source

Is there a simple method to convert an 8-bit grayscale JPEG from Canvas using client side technologies in a web browser (such as HTML5, canvas, WebGL, and JavaScript)? Are there any pre-made JavaScript libraries available for use, without requiring extens ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...