I aim to display the outcome of Math.round(score * 0.10), however, what ends up being displayed is the outcome of that outcome

I am working with the following JavaScript code:

score -= Math.round(score * 0.10);
$('.sc').text(score);
$('.score').text('-' + Math.round(score * 0.10));

This code is designed to deduct 10% from a given score without any decimals. For example, if we have a div with class "sc" and the score is initially set to 456, we would like to take away 10% from this value.

The following line of code

score -= Math.round(score * 0.10);
calculates that 456 - 46 = 410, and then $('.sc').text(score); updates the text in the "sc" div to display: 410

However, another div with the class "score" needs to display the deducted amount, which should be 46. Unfortunately, using

$('.score').text('-' + Math.round(score * 0.10));
shows 10% of 410 rather than the original 456.

How can I correctly display the deducted amount (46) in the ".score" div? Any suggestions would be greatly appreciated.

Thank you,

Maurice

Answer №1

Instead of repeatedly calculating the deduction, it is better to monitor its value.

let penalty = -Math.round(score * 0.10); 
score += penalty; 
$('.total-score').text(score);
$('.deduction').text(penalty);

Answer №2

Consider using a new variable for an alternative approach.

var updatedScore = Math.round(score *= .9);
$('.sc').text(updatedScore);
$('.score').text('-' + (score - updatedScore));

In this scenario, score *= .9 calculates 90% of the score and then subtracts it from the original value.

The reason for doing it this way is to ensure that any mathematical operations are performed on the most current value rather than the initial one.

Answer №3

First, assign the rounded score to the variable. Next, perform another rounding operation on it.

Answer №4

Save time by avoiding subtraction:

$('.sc').text(Math.round(score*0.9));
$('.score').text("-" + Math.round(score*0.1));

Answer №5

$('.sc').text(Math.round(result * .9));
$('.score').text('-' + Math.round(result * .1));

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

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

How can I prevent users from selecting text when they right click using JavaScript?

My custom context menu on canvas works well, but I'm facing an issue with Text elements. When I try to right-click on a text element, it triggers text selection as if double-clicking. I attempted to use the following code: document.addEventListener(& ...

Issue with dialogue not appearing when clicking on a table cell

UPDATE: I am facing a challenge with this code not displaying a dialog upon click.: The issue lies in the fact that nothing happens when the Title is clicked. Any suggestions? The data is present, as removing the .hidden CSS class reveals it. $(". ...

What causes the error message "Why does the 'do not alter Vuex store state outside mutation handlers' error occur?"

Although I've searched through similar topics, none of the solutions seem to fix my issue. I've been attempting to integrate Three.js with Vue3 (+Vuex). I carefully followed this tutorial: and it works perfectly on that site. However, when imple ...

Enhance the functionality of the button by implementing AJAX with the use of data

I am currently working on implementing an update function without using forms. Instead, I am utilizing data-* attributes and ajax. My goal is to prevent the button from triggering after updating the values. However, I am facing an issue with my script as ...

Updating the value within a nested object in React's useState function

Here is an example of how I am managing state using useState: const [data, setData] = useState([ { id: 1, options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }] }, { id: 2, options: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }] } ]); ...

Verifying the similarity of usernames using a JSON array

My attempts to create a function that verifies if app.account_username matches a username in a json array are just leading me in circles. This is how the json array is structured { "data": { "id": 32607158, "with_account": "user1", "with_account_id": 84 ...

How can we sort an array in JavaScript based on a particular parameter rather than the default sorting behavior that considers other parameters as well?

When organizing an array based on a specific parameter, it currently takes into account another parameter as well. However, I want to prioritize sorting based solely on my chosen parameter. To achieve this, I have developed a helper function that properly ...

Is it possible to use regex to replace all content between two dashes, including any new

I have a specific set of dashed markers that I am looking to update based on the content of $("#AddInfo"). If the field is not empty, I want to replace everything between the markers. Conversely, if $("#AddInfo") is empty, I need to remove all text betwe ...

Adding Floating Point Numbers in TypeScript Objects

Recently, I've been encountering some strange results while trying to sum up my floating point values. The output seems off with 8 decimal places and other unexpected outcomes. All I really want to do is add up the protein values of various objects to ...

Delaying the activation of the code until the image upload is complete

I'm having trouble synchronizing code to upload an image using a vue composable, wait for the upload to finish, and then store the Firebase storage URL into a database. Despite getting the URL, the success code fires before the upload is complete. My ...

Show the current server time on the client side using Meteor

Is there a more efficient way to display the server's time as a running clock (h:m:s) on the client using Meteor? Traditional JavaScript/PHP methods involve fetching the server time periodically and calculating the time difference with the client. Bu ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

Error: Unable to access the 'comments' property of a null value

Encountering an issue when trying to add comments to a post, resulting in the error message: TypeError: Cannot read property 'comments' of null Post routes: router.post("/", async (req, res) => { console.log(req.params); Post.findById(r ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

ERROR: An issue occurred while attempting to resolve key-value pairs

Within my function, I am attempting to return a set of key-value pairs upon promise completion, but encountering difficulties. const getCartSummary = async(order) => { return new Promise(async(request, resolve) => { try { cons ...

Switching up the menu choices does not result in a shift in the active class, despite attempting the workaround outlined in the following link

Currently, I am working on a website which can be accessed at the following link: . You can find a helpful example link below. How to change active class while click to another link in bootstrap use jquery? Now, I will showcase the code that I have writt ...

What is the best way to incorporate a fresh array into the existing array element stored in local storage?

I stored a group of users in the local storage: let btnSignUp = document.getElementById("btnSignUp"); btnSignUp.addEventListener('click', (e) => { let existingUsers = JSON.parse(localStorage.getItem("allUsers")); if (existingUsers == null ...