Unable to assign decimal values to the tooltip value in Angular's Ng bar chart

I'm currently working on my Angular project with ngChartjs, and I've run into a conflict regarding the tooltip values.

https://i.sstatic.net/NBKCJ.png

For example, if the value is 6131327.319655154, I have tried formatting it to 6131327.31 using the code snippet below, but it's not functioning as expected.

tooltips: {
      callbacks: {
        label(tooltipItem, data) {
          return tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }, },
    },

This is the code I am using:

HTML

<canvas ngChartjs
                [datasets]="barChartData"
                [labels]="barChartLabels"
                [options]="barChartOptions"
                [colors]="barChartColors"
                [legend]="barChartLegend"
                [chartType]="barChartType"
                [colors]="colors">
        </canvas>

.ts // Bar Chart

 public colors = [
    { backgroundColor: '#29aae2' },
    // { backgroundColor: '#7f9ebc' },
  ];
  barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true,
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: false,
          labelString: 'Month'
        },
        gridLines: false,
        ticks: {
          display: true,
          beginAtZero: true,
          fontSize: 13,
          padding: 10
        }
      }],
      yAxes: [{
        display: true,
        scaleLabel: {
          display: false,
          labelString: 'Value',
        },

        gridLines: {
          drawBorder: false,
          offsetGridLines: false,
          drawTicks: false,
          borderDash: [3, 4],
          zeroLineWidth: 1,
          zeroLineBorderDash: [3, 4]
        },
        tooltips: {
          callbacks: {
            label(tooltipItem, data) {
              return tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }, },
        },
        ticks: {
          /*    max: 100,*/
          // stepSize: 20,
          display: true,
          beginAtZero: true,
          fontSize: 13,
          padding: 10,
          // stepSize: 100000,
          callback(value) {
            const ranges = [
              { divider: 1e6, suffix: 'M' },
              { divider: 1e3, suffix: 'k' }
            ];
            function formatNumber(n) {
              // tslint:disable-next-line:prefer-for-of
              for (let i = 0; i < ranges.length; i++) {
                if (n >= ranges[i].divider) {
                  return (n / ranges[i].divider).toString() + ranges[i].suffix;
                }
              }
              return n;
            }
            return ' ' + formatNumber(value);
          }

        }
      }]
    }
  };
  barChartLabels: string[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  barChartType = 'bar';
  barChartLegend = true;
  barChartColors: Array<any> = [
    {
      backgroundColor: this.themeColors.blue,
      borderWidth: 0
    },
    {
      backgroundColor: this.themeColors.blueLight,
      borderWidth: 0
    }
  ];
  barChartData: any[] = [
    {
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      label: '2020',
      categoryPercentage: 0.70,
      barPercentage: 0.70,
    },
    {
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      label: '2021',
      categoryPercentage: 0.70,
      barPercentage: 0.70,
    }
  ];

Has anyone encountered a similar issue and found a solution?

Thanks

Answer №1

For me, the solution was to include toFixed(2)

callbacks: {
          label: function(tooltipItem, data) {
              return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
          }
      }

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

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Omit the timezone details when initializing a new Date object in Angular

Encountered a problem while testing the following line of code console.log(JSON.stringify(new Date('2016-06-15 10:59:53.5055'))); The result I'm getting is "2016-06-15T08:59:53.505Z", but I was expecting "2016-06-15T10:59:53.505Z" Is ther ...

Switch the class of the Parent Component to that of the Child Component

Dashboard.html <nav #nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <button class="nav-link active" id="nav-categories-tab" data-bs-toggle="tab" data-bs-targ ...

Why does my test in Angular 2 e2e protactor fail when I do not include browser.sleep()?

While working on my e2e tests, I encountered an issue with a custom select dropdown component I created. When trying to select items in the dropdown, I found that I had to use browser.sleep(...) in my test for it to pass. If I don't include this sleep ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

Ways to implement modifications to two separate input fields utilizing a single function

I am in the process of developing a performance comparison widget using Angular. The purpose of this widget is to compare the performance of the current Calendar year with the Previous Calendar Year, as well as the performance from the current Year-to-date ...

Transitioning a reusable modal component from AngularJS to the latest version of Angular

As I transition my application from Angularjs 1.X to Angular 14, I've come across an issue with a reusable modal popup (a modal that displays a message with ok/cancel buttons). Below is the Angularjs code snippet from the controller: $rootScope.showCo ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

Could JSON be the solution for combining a number and a string in a single key-value pair?

I am working on defining a nested JSON object that will store a key value pair with an integer (representing the amount of something) in use case 1, and a key value pair with a string (UUID) in use case 2. The ultimate goal is to analyze this data in futu ...

Angular 10 is not displaying images despite receiving the image path from an API

Despite my API returning the image path for the product, my Angular application is not displaying the image. https://i.sstatic.net/PhD1s.png HTML Code <ng-container *ngFor="let prod of productData"> <div class="row p-2 b ...

Retrieving the previous and current URL in Angular 8

Need help setting variables prevUrl and currentUrl in Angular 8 by fetching previous and current URLs. The scenario involves two components - StudentComponent and HelloComponent. When transitioning from HelloComponent to StudentComponent, I face an issue. ...

Having trouble importing the datamap library into the HTML of an Angular 2 application

I am currently in the process of developing a small Angular 2 application for educational purposes, and my intention is to incorporate datamaps for the map interface. However, there is no directive available for this library yet, so I am experimenting wit ...

Why isn't the Angular2 ngIf directive updating the DOM?

I am encountering issues with finding the right expression for ngIf to evaluate properly. After following a basic Angularfire2 example, I have successfully managed to log in and out. import { Component } from '@angular/core'; import { AngularFi ...

Transfer information to a form using the <mat-select> element

Looking for a way to display user roles in Angular using a mat-table that were previously selected with <mat-select>. When I use a regular <select>, a new entry shows up in the table, but the styling is not ideal. <label>Role</labe ...

Angular 2: Finding the object with the highest attribute value in an array of objects

I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript? i ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

Angular 5 throwing an error - trying to access a property that is undefined

In my form, each div contains a label, checkbox, and input field. When the menu is opened, all checkboxes are initially unchecked, disabling all input fields. You can then enable an input field by checking its corresponding checkbox. I attempted to implem ...

Azure Function (.NET 7, v4) encountering Cross-Origin Resource Sharing problem

I am experiencing a CORS problem with my Azure function written in C# using .NET 7. It is being called from my Angular application. Interestingly, the same function works fine when called from Postman with the same request body as the Angular application. ...

The power of negative multiplication in TypeScript and React

I am working with a state variable called sortDirection const [sortDirection, setSortDirection] = useState<1 | -1>(1); My goal is to allow a button to toggle the state variable like this setSortDirection(sortDirection * -1); However, I encounter a ...

What is the appropriate interface for determining NavLink isActive status?

In the process of crafting a "dumb" component using NavLink, I am defining the props interface for this component. However, I encountered an issue when trying to include isActive in the interface. It's throwing errors. I need guidance on how to prope ...