Vue.js - when it comes to rounding off digits, I keep getting unexpected results

Currently, I am in the process of calculating my totals and I need to ensure that they are fixed to 2 decimal places. Here is a snippet of my code:

this.selectedCompaniesDetails.forEach((company) => {
                            if(company.id == p.company_id)
                            {
                                if (!tot[p.company_id])
                                {   tot[p.company_id] = [] }
                                    const numberPrice = parseFloat(p.price)
                                
                                 tot[p.company_id].push(numberPrice)
                            }
                        });

However, I am facing an issue with the parseFloat(p.price) function which seems to be returning strange values. To visualize this problem better, take a look at my screenshot below.

Answer №1

Here is an example to consider:

let number = 5.56789;
let roundedNumber = number.toFixed(2);

console.log(number);
console.log(roundedNumber);

Answer №2

For rounding a number to two decimal places, you can use the following code snippet:

function roundToTwo(num) {
   return +(Math.round(num + "e+2")  + "e-2");
}

let number = 139.605;
let round = roundToTwo(number)
var f = number .toFixed(2);

console.log('original', number);
console.log('expected', 139.61);
console.log('(Correct)round', round);
console.log('(Wrong)toFixed', f);

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

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

The Angular JSONP feature is malfunctioning

I'm attempting to utilize a jsonp call with the following code, but it doesn't appear to be functioning as expected. Code var url = 'http://z:15957/Category/Categories?callback=JSON_CALLBACK'; $http.jsonp(url).success(function (data) ...

Loop through the tabs in a for loop until reaching the specified length

I have a switch case function inside a modal in Vue. My goal is to create tabs or screens for different components. <div v-switch="tabnumber"> <div v-case="1"> <form-component> ...

Activate the initial tab in JQuery UI accordion upon initialization

Hello, I have implemented a simple sidenav menu on my website. It consists of parent items and child items structured according to the h3 > div format as suggested by JQuery's documentation. My challenge now is to automatically open the "active" tab ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...

Froala text area is unexpectedly visible when I attempt to cover it with a partially see-through mask

The website I'm currently developing features a semi-transparent overlay that dims the screen with a light-colored message displayed on top. This overlay and message are shown whenever there is a background process running. Everything was running smoo ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Unreliable Response from JEditable

I have encountered an unusual behavior while using the JEditable jQuery plugin to update data on my webpage. One specific field is not updating as expected, instead displaying the following message: EM29UPDATE NetLog SET grid = 'EM29&apo ...

AngularJS mobile navigation menu toggle not functioning properly with the close feature

I am currently developing a simple Single Page Application (SPA) using an HTML template. The template includes a mobile navigation menu, but I am facing issues with it not closing when navigating through routes in AngularJS. Can anyone provide guidance on ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

Problem with Gulp-Watch Functionality on Windows 7 - Node.js, NPM, and Gulp All Up and Running Fine

As someone who is new to the world of Node.js, NPM, and other modern tools designed to improve productivity and workflow, I find myself faced with some challenges. Below are the specifications: Node version - v8.10.0 Gulp CLI version - 2.0.1 Gulp Loca ...

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Tips for creating a Nuxt.js server-side rendering (SSR) setup with partially static pre-rendered

While there is plenty of information available on Nuxt SSR and full static sites, I am struggling to find a guide on how to create a hybrid SSR with static pages combined. Currently, I am working on a website using Nuxt SSR and my goal is to statically ge ...

When attempting to send a POST request to /api/users/login, the system returned an error stating that "

Is there a way to make a post request to the mLab Database in order to determine if a user account already exists? The server's response states that the User is not defined. Can you please review my code? // @route post api/user/login# router.post(& ...

Adjustable value range slider in HTML5 with ng-repeat directive in AngularJs

I am facing a problem with my HTML5 range slider. After setting a value (status) and sending it to the database, when I reload the page the slider's value is always set to '50'. The slider is being generated within an ng-repeat from AngularJ ...

Step-by-step guide to selecting a specific point on an HTML5 canvas using Python's selenium webdriver

Looking to automate interactions with a simple HTML5 application on a website using Selenium webdriver in Python with Firefox on Linux. The challenge is clicking a button on an HTML5 canvas, then dragging one or two objects around the canvas post-button cl ...