Calculating a total without the need to round it to the nearest two decimal points

Excuse my lack of expertise in this area. I recently asked a question about rounding off numbers to two decimal places. Now, how can I calculate the sum of these numbers but display only the two decimals without rounding them off? I am working with JavaScript.

For example: 12.876 + 36.278 = 49.154. I want the answer to be... 49.15 only. Or another example: 12.876 + 1 = 13.876. I need the answer to be... 13.87

Below is my current code (which rounds off to two decimal places)

function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*10)/10;
document.addition.civ123.value=valNum1;
}

Gratitude to everyone who assists me regularly! :)

Answer №1

Math.round(N * 100) / 100

This code will round off to the nearest hundredth place; Math.floor() ensures rounding down.

Answer №2

It is important to note that Math.floor(N * 100) / 100 does not always yield the expected result.

For instance,

When applying this formula, 4.56 may actually become 4.55.

Answer №4

An age-old inquiry, yet lacking a satisfactory response until now. As highlighted by @user3006769, some numbers fail to produce the desired outcome when applying Math.floor(N*100)/100.

An alternative method involves determining the number of digits preceding the decimal point, converting the number to a string, truncating any characters beyond the second decimal place, and reconverting it back to a number:

function roundDownDecimals(num, decimals) {
  const preDecimalDigits = Math.floor(num).toFixed(0).length;
  return parseFloat(num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1));
}

roundDownDecimals(4.56, 2);
// results in 4.56

roundDownDecimals(13.876, 2);
// results in 13.87

roundDownDecimals(4.10, 2);
// results in 4.1

To maintain trailing zeroes, omit the parseFloat function.

function roundDownDecimals(num, decimals) {
  const preDecimalDigits = Math.floor(num).toFixed(0).length;
  return num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1);
}

roundDownDecimals(4.10, 2);
// results in "4.10"

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

Checking the URL in Redux Form

I am currently using the redux-form library to manage my form in React Redux. I have successfully implemented validation for fields like email and name. However, I am facing an issue with validating a URL field in redux-form. What specific format should I ...

Most effective method for eliminating an item from an array with AngularJs

I have an array of objects that I want to modify by removing multiple objects from it. The following code is currently achieving this successfully, but I'm curious to know if there is a more efficient way to accomplish this task. This process involv ...

Achieve video lazy loading in JavaScript or jQuery without relying on any external plugins

I've been experimenting with lazy loading videos using jQuery. While I've had success with lazy loading images and background-images using the same technique, I ran into issues when trying to apply it to videos. Here's what I've tried s ...

Retrieve the id of an element from a JSON object

Dealing with quotes, single or double, can sometimes pose a challenge. I am working on a JavaScript function that sends data to a PHP file and receives a JSON response. Everything seems to be functioning correctly, except for the part where I need to out ...

Status of Google Sheets sidebar being opened or closed

I am currently seeking a method to monitor the status of the sidebar within Google Sheets. My understanding is that I can ascertain which sidebar HTML has been accessed by establishing a global variable before the HTML content is presented. Given that onl ...

Why does calling $resource (or $http) from inside a callback in Cordova and AngularJS result in a 404 error?

After successfully transitioning my functional angularjs web app to Cordova and compiling it for iOS, I encountered an issue while testing the app on iOS. When trying to access a local file from inside a callback response (after successfully accessing anot ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

Encountering a "404 method not found" error in the developer console when handling meteor collections

Having an issue while trying to insert a document into my meteor collection using an autoform generated from my Mongo schema. Upon clicking the submit button, I am encountering a "method not found [404]" error in the developer console. I suspect the proble ...

I am looking to retrieve a particular entry from a JSON data array and make some modifications to it

Initially, I fetched JSON data from the web server using the following code: $.getJSON(url,function(){ //my callback function; }); Now, I have received the data in the format shown below: {entries:[{title:'foo',id:'UUID',finished:nul ...

Cookie Strategy for Managing Popups Site-wide

Below is a script that will trigger a popup after 60 seconds of page load. This script also creates a cookie to prevent the popup from appearing more than once. The cookie expires when the user's session ends. However, the popup only appears on the e ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

What is the best way to sum two values in an array object and then replace the first value with the result?

I have an array containing two objects: let xyz = [ {amount: 1000, rate: 4}, {amount: 100, rate: 2}, {amount: 700, rate: 1} ]; The task is to multiply amount * rate and update the values in the amount key. Desired output: let result = [ {amo ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Tips for navigating between slides on a CSS carousel?

I am currently in the process of creating a CSS-based carousel .carousel { -webkit-scroll-snap-type: x mandatory; -ms-scroll-snap-type: x mandatory; scroll-snap-type: x mandatory; -webkit-overflow-scrolling: touch; overflow-x: scro ...

Exploring the application of Checklist-model in Angular

My goal is to have departments as titles and employees as subtitles. When the user checks a department title, all associated employees should also be checked. I am implementing this using fieldset and table in HTML with ng-repeat. It seems similar to this ...

Tips for excluding a value in a Vue loop

Is there a way to exclude the value "Three" from the loop in the following code snippet? <script > const routes = [ {name: 'One', value: 24}, {name: 'Two', value: 25}, {name: 'Three', value: 26}, {name: ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

What is the best way to ensure that the bootstrap nav tab content fits perfectly on one line?

Check out this bootstrap navbar example You can see a screenshot here. <ul class="nav nav-tabs" style="display: inlne-block"> <li class="nav-item" style="text-align: center; display: inline;"> <div> <a class="nav ...

I'm currently leveraging Vue.js and Python Flask for my backend development. I'm looking to establish some local variables. What is the best way to accomplish this?

Here is my Vue js file where I am utilizing two URLs from localhost. My goal is to create a configuration file that will allow me to make changes in one place and have those changes reflected throughout. <template> <div> <div class="glob ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...