Tips for determining the overall percentage breakdown of 100% based on the individual denominator for every column within angular 8

In my code, I have a simple function that calculates the sum of numbers and strings in columns within a table. The sum calculation itself works fine and provides accurate results. However, the problem arises when I attempt to divide the total sum of each column by 100, as it gives me incorrect values.

Here is an example scenario:

I have a sum of 969.35 in column A. When I try to divide this value by 100, I expect to get 9.69. Instead, I am getting 0.51. This discrepancy has perplexed me as to why this calculation is going wrong.

This is how I'm currently implementing the sum calculation:

getSum(columnNumber) {
    let sum = 0;
    const columnNumberToPropertyMap = [
      "id",
      "teamNumber",
      "rural",
      "completed",
      "entirehouseholdabsent",
      "postponed",
      "refused",
      "vacant",
      "dwelling"     
    ];
    const property = columnNumberToPropertyMap[columnNumber];
    return this.rural.reduce((acc, curr) => {
      //const adder = Number(curr[property]) || 0;
      const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
      sum = acc + adder
      return sum.toFixed(2);
    }, 0);
}

The above code successfully calculates the sum for each column.

Now, here's how I'm trying to calculate the percentage:

 getPercentage(columnNumber) {
        let sum = 0;
        let percentage = 0;
        const columnNumberToPropertyMap = [
          "id",
          "teamNumber",
          "rural",
          "completed",
          "entirehouseholdabsent",
          "postponed",
          "refused",
          "vacant",
          "dwelling"     
        ];
        const property = columnNumberToPropertyMap[columnNumber];
        return this.rural.reduce((acc, curr) => {
          //const adder = Number(curr[property]) || 0;
          const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
          sum = acc + adder
          percentage = (sum)/100;
          return percentage.toFixed(2);
        }, 0);
      }

If anyone can point out what mistake I might be making or suggest a solution, it would greatly help me understand and resolve this issue.

Answer №1

To resolve the issue, make sure to follow this advice. Avoid dividing each time as it causes problems. It's important that the percentage calculation is done outside of the reduce loop.

(this.urban.reduce((acc, curr) => {
          //const adder = Number(curr[property]) || 0;
          const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
          sum = acc + adder
          percentage = sum;
          return percentage ;
        }, 0) / 100).toFixed(2);

Answer №2

According to Angular guidelines, it is discouraged to use Number() && String().

To retrieve a value from a formControl, you can do so like this:

const completeFormValue = this.formName.getRawValue();

The code above will return a JSON object structured like this:

{formCtrl1: ctrl1Value, formCtrl2: ctrl2Value, ......etc}

If you need the value of a specific formControl, you can access it like this:

this.formName.get('formControlName').value

Ensure that the particular field (assuming it's an input field) only accepts numbers so that you receive only numbers in the

this.formName.get('formControlName').value
.

IF YOU PREFER AN ALTERNATIVE METHOD, consider using parseInt() or parseFloat() instead of Number()

By using parseInt() and parseFloat(), you will obtain precise numerical values.

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

Presenting CSV data in a tabular format using Angular and TypeScript

I am facing an issue with uploading a CSV file. Even though the table adjusts to the size of the dataset, it appears as if the CSV file is empty. Could this be due to an error in my code or something specific about the CSV file itself? I'm still learn ...

Using ngFor to create dynamic columns in a Kendo Grid

Looking at this code snippet <kendo-grid-column title="{{localizationKeys.adempimenti.organizzazione.responsabile}}" field="addettiGrid"> <li *ngFor="let addetto of addettiGrid; let i=index"> <div>{{addetto}}</div> ...

Turning an angular API into a synchronous one: A step-by-step guide

My goal is to perform consecutive http calls to a REST service, with each call requiring a unique valid token in the header. The challenge arises when multiple components initialize simultaneously and make "get" calls at the same time using the same token. ...

Exploring the world of Wordpress Rest API for retrieving posts

I'm attempting to display all of my posts from my WordPress website. Currently, there are 2 posts available which can be viewed in the JSON file: View export class HomePage { url: string = ‘http://feederhorgasz.000webhostapp.com/wp-json/wp/v2/posts ...

Looking to create an interactive audio experience for users with Angular by playing audio on their click events sourced from Firebase?

I am currently developing a dashboard where I aim to enable users to play specific audio files that they select from a table by clicking on a play button. These audio recordings are stored in Firebase storage. The issue I am facing is that when I manually ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Troubleshooting Angular 2 component tests using Jasmine spies: How to resolve the "Http provider not found" error

I'm currently testing an Angular 2 component that utilizes a service. The service has Http injected into it, but I'm only interested in mocking and spying on the service's method call rather than testing the Http functionality itself. While ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Learn the process of generating an ID and dynamically updating its content using Angular

I have a coding challenge where I need to dynamically create an ID and retrieve it in order to change its content upon clicking. Here is the code snippet: <div class="row" *ngFor="let row of [1, 2, 3]"> <button (click)=&quo ...

`What specific type should be assigned to the custom styled input component in MUI?`

Hey team! Would you mind helping me out with this issue? The Mui documentation suggests setting a type for a Mui Styled component like this: const MyComponent = styled(MuiComponent)(({ theme }) => ({ // styling })) as typeof MuiComponent This method ...

Issue with Bootstrap Angular dropdown menu malfunctioning within ChildRoute

Recently, I have been working on integrating admin bootstrap html with Angular. As part of this integration, I added CSS and JS files in angular.json as shown below: "styles": [ "src/styles.css", "src/assets/goo ...

Displaying JSON data using FormControls in Angular 5

Upon receiving Json values from the server, I am encountering an issue while binding them to respective textboxes. The problem arises as the value in the textbox appears as [object object] <h1>{{title}}</h1> <h3>Catalog</h3> ...

Guidelines on adjusting Angular mat-button attributes using an observable stream

Below is the code snippet I am working with: <button mat-button [disabled]="offline() | async" [textContent]="scanning() ? 'Stop' : 'Start'" (click)="scanning() ? onScanStop() : onScanStart()"> </button> The functi ...

Guide to creating content on an NFC tag with Ionic

I am struggling with my button calling the test2 function and the code I have is not working as expected. Here is what I currently have: import { Component } from '@angular/core'; import { NFC, Ndef } from '@ionic-native/nfc/ngx'; @Com ...

Creating various subtypes for graphql-codegen

Currently, I am utilizing the typescript-operations package within the framework of the graphql-codegen library. Previously, I was accustomed to using Apollo's deprecated codegen and appreciated how it exported types seamlessly. For example, let&apos ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Several cucumber reports are showing an error message containing special characters

I am encountering an issue in the multiple cucumber report where error messages are being displayed with special characters. Is there a way to format them properly? I am currently learning Playwright, Typescript, and CucumberJs and generating reports for m ...

What is the best way to include documentation for custom components using jsDoc?

Within my Vuejs inline template components, we typically register the component in a javascript file and define its template in html. An example of such a component is shown below: Vue.component('compare-benefits', { data() { // By return ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...