Issue with Angular 9 Json pipe not showing decimal values

My JSON data looks like this:

this.data = {"eoiStatistics": [
{
  "dateRange": {
    "explicitStartDate": "1997-01-01T00:00:00",
    "explicitEndDate": "2019-07-01T00:00:00"
  },
  "outstandingApplicationCount": 0.0,
  "pendingApplicationCount": 24.0,
  "approvedApplicationCount": 0.0,
  "declinedApplicationCount": 0.0,
  "closedApplicationCount": 0.0 }]}

When I use the json pipe {{data | json}} in my application, it displays as follows:

{"eoiStatistics": [
{
  "dateRange": {
    "explicitStartDate": "1997-01-01T00:00:00",
    "explicitEndDate": "2019-07-01T00:00:00"
  },
  "outstandingApplicationCount": 0,
  "pendingApplicationCount": 24,
  "approvedApplicationCount": 0,
  "declinedApplicationCount": 0,
  "closedApplicationCount": 0
}]}

Although the value is 24.0, it's displayed as 24 due to the nature of how numbers are formatted. Is there a way to retain the decimal point and display it in my application?

Answer №1

Managing this situation might be challenging, but there are a couple of solutions you can consider. You could either modify the data before sending it or adjust how the data is presented:

  1. Convert the json value to a string instead of a number:
"pendingApplicationCount": "24.0"
  1. Change the display format. Since you are using angular, utilize the DecimalPipe pipe
<div>{{ data.pendingApplicationCount | number: '1.1-5' }}</div>

Answer №2

Building on the response provided by @PoulKruijt, it is evident that the JsonPipe serves as a simple transform function encapsulated within a single line of code.

transform(value: any): string {
  return JSON.stringify(value, null, 2);
}

An alternative approach could involve creating a custom pipe with a replacer parameter in the JSON.stringify() method.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'jsonDecimal'
})
export class JsonDecimalPipe implements PipeTransform {

  transform(value: any, length?: number): any {
    return JSON.stringify(
      value, 
      (key: any, value: any) => {
        if (typeof value === 'number') {
          return Number(value).toFixed(length);
        } else {
          return value;
        }
      }, 
      2);
  }

}

Illustrative Example 1

This permits specifying the desired decimal precision within the template.

<div>{{ data | jsonDecimal:1 }}</div>

resulting in the representation of numbers with one decimal place.

Output Displayed in Template

{ "eoiStatistics": [ { "dateRange": { "explicitStartDate": "1997-01-01T00:00:00", "explicitEndDate": "2019-07-01T00:00:00" }, "outstandingApplicationCount": "0.0", "pendingApplicationCount": "24.0", "approvedApplicationCount": "0.0", "declinedApplicationCount": "0.0", "closedApplicationCount": "0.0" } ] }

Illustrative Example 2

You have the flexibility to define more precise decimals for additional trailing zeroes.

<div>{{ data | jsonDecimal:4 }}</div>

demonstrating

{ "eoiStatistics": [ { "dateRange": { "explicitStartDate": "1997-01-01T00:00:00", "explicitEndDate": "2019-07-01T00:00:00" }, "outstandingApplicationCount": "0.0000", "pendingApplicationCount": "24.0000", "approvedApplicationCount": "0.0000", "declinedApplicationCount": "0.0000", "closedApplicationCount": "0.0000" } ] }

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

Using jQuery to loop through divs, identify unique ones, and then add text from a specified value to a span element

I've been delving into the world of jQuery, asking numerous questions and providing some answers as a beginner myself. Currently, I have a good understanding of how to utilize jQuery for tasks such as adding CSS styles to a div and inserting text into ...

Enhancing Image Quality upon Hovering

Is there a way to prevent the content of the article from moving when an image becomes absolutely positioned? The issue I am facing is that the image overlaps its container with overflow: hidden only when the img is absolute positioned. article { back ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

Hovering over the Laravel Breeze dropdown will activate a dropdown feature

Recently, I've been working on a project with Laravel Breeze and have been utilizing some default components. The dropdown component used in the navigation bar caught my attention. By default, it requires a click for the menu to drop down below. Howev ...

Tips for utilizing canReuse and routerOnReuse in Angular 2

I've reviewed the information provided in this link, but I'm still unsure about how to effectively utilize it. My requirement is straightforward—I need to update a parameter in the URL without constantly sending API requests, which are current ...

How can I apply styles to table cells based on their data type using HTML and CSS?

On a webpage, I have a standard table/th/tr/td setup that presents tabular information. The columns can be rearranged: product|price|date price|product|date date|product|price ... and so forth. However, the original order remains consistent for each disp ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Can you explain the connection between CSS and WebKit?

Lately, the tag "webkit" has caught my eye on various questions. These inquiries typically pertain to web-related topics like CSS, jQuery, website layouts, and cross-browser compatibility problems... But what exactly is "webkit" and how does it interact w ...

Maximizing the width of an absolute div element inside a container

Looking at this demo, you'll notice that the header remains fixed. However, my issue lies in getting the absolute <div> inside the <th> to occupy 100% of the width of the <th> When I set width: 100% for the <div>, it expands t ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

It appears that IE 10 is having trouble displaying modals, possibly due to a compatibility issue with jQuery 1.7.1's animate function

By visiting www.carsense.com and clicking on the login link in the top-right corner, you may notice that the curtain appears but the modal itself does not display, even though it exists: If you locate id="content1" and modify the inline opacity to 1, the ...

Padding-left may cause text to not wrap correctly

Every link in the left menu has a padding-left: 15px;. This is done to accommodate a background image (the blue arrow). However, when text wraps (like in "Paintings, prints, and watercolours"), it seems to ignore the padding. I've searched extensive ...

When the jQuery Div is moved to the right, it gradually shrinks in size, yet remains unchanged when

I have been making updates to this page, which you can view here. When you select "Let's Get Started" and then proceed with the right arrows, the divs smoothly move to the left without shrinking. However, when clicking on the back or left arrows, the ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Is it feasible to dynamically incorporate various versions of Bootstrap within the head tag?

The CMS I'm currently working with has a strict dependency on a specific version of Bootstrap. However, there are features from Bootstrap 3.3.6 that I need based on the page being loaded in the browser. I initially considered using JavaScript or jQue ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Implementing MySQL in JavaScript code leads to various possibilities

I am working on a web application that requires retrieving values from a MySQL database. The process involves: PHP code generates an HTML page successfully. Clicking a button updates a cookie, which also works. Using the cookie in a MySQL query, which is ...

Issue with content not wrapping inside the body tag (apart from using float or setting body and html to 100

Why on earth is the body/html or .main div not wrapping my .container div's when the browser width is between 767-960 px?! This is causing horizontal scrolling and I am completely baffled. This should definitely be working! The only code I have is: ...