Angular trailing zero problem

There is a function that returns a number. Within this function, a string '1.10' is present, which is then converted to a number using the Number method.

The output obtained is 1.1, but the desired output is 1.10.

I have tried using methods like Number, parseFloat, and +, but have not been successful in achieving this in Angular.

Answer №1

Numbers should not contain trailing zeros on either side.

1.1 -> considered valid

1.10 -> considered an invalid number

01.1 -> also considered an invalid number

If there is a need to display the output with trailing zeros, the Angular DecimalPipe can be used.

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div>string: {{str}}</div>
    <div>number: {{num}}</div>
    <div>number formatted with decimal pipe: {{num | number: '0.2-2'}}</div>
  `,
})
export class App {
  name = 'Angular';
  str: string = '1.10';
  num: number = parseFloat(this.str);
}

bootstrapApplication(App);

Check out the Stackblitz Demo

Answer №2

One way to achieve this is by creating a custom pipe:

ng generate pipe trailing-zero

Then update the generated pipe as follows:

@Pipe({ name: 'trailingZero', pure: false })
export class TrailingZeroPipe implements PipeTransform {
  transform(value: number | string, decimalPlaces: number = 1): string {
    if (typeof value === 'string') {
      value = Number(value);
    }
    return value.toFixed(decimalPlaces);
  }
}

If you are using NgModule, make sure to import it. Otherwise, if your application is based on standalone, import the pipe where you intend to use it.

For a working demonstration, check out this stackblitz link.

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

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

Is there a potential issue in Next.js 14 when utilizing the "useClient" function alongside conditional rendering in the app/layout.tsx file?

Within my app, there is a Navbar that will only be visible when the route is either "/" or "/teachers". The Navbar will not appear on the dashboard page ("/dashboard"). I achieved this using conditional rendering in the app/layout.tsx file. "use clien ...

Displaying data issue with Typescript typed array

While working with Angular 7 and Typescript 3, I encountered an issue where I was trying to pre-populate an array of ingredients in a service for use in a component. However, when I checked the console output, the array was showing empty objects. If I ini ...

Something went wrong: You cannot use this command while the Angular CLI is running within a workspace

My angular project suddenly started showing the error message "Error: This command is not available when running the Angular CLI inside a workspace." Now, I can only use "ng serve" and not "ng n c". Any ideas on how to fix this? Angular Version: Angular C ...

FirebaseError: Trigger parsing error: Module 'grpc' not found

I'm currently working on setting up an Angular4 application with Server Side Rendering (SSR) using Angular Universal and Firebase Cloud Functions. While the application works smoothly with ng serve, I encountered an issue after building the app and s ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

What is the method for determining the data type of a column in an Excel sheet that has been

Currently, I am utilizing the XLSX npm library to convert an Excel sheet into JSON format. However, all of the retrieved data is currently being returned as strings. To see a demo of the XLSX read process, you can visit this Stackblitz demo Is there a w ...

Tips for implementing logic on input values in Angular 4

How to increase a value from a form in app.component.html by 2 and display it <input type="number" class="form-control" [(ngModel)]="value" /> <!-- <p><button (click)="submit()" class="btn btn-warning btn-sm">Submit</button ...

Mastering the Art of Mocking Asynchronous Methods in Node.js Using Jest

I have the following files: |_ utils.js |_methods.js I am currently conducting unit testing for rest.js methods, where the content of the file is as follows: methods.js import Express from 'express' import { add_rec } from './utils' ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

Arrange items by their keys while keeping their current values in order to correspond to the array sequence

I have two sets of data. First one is in the form of (footerMenuOptions): [{Home: true}, {About: false}, {Features: false}, {Contact: false}]  The second set is in the form of (this.navbarMenuOptions): ["Home", "About", "Features", "Contact"] Occasio ...

The Next.js template generated using "npx create-react-app ..." is unable to start on Netlify

My project consists solely of the "npx create-react-app ..." output. To recreate it, simply run "npx create-react-app [project name]" in your terminal, replacing [project name] with your desired project name. Attempting to deploy it on Netlify Sites like ...

Guide on displaying information on a pie chart in Angular 2 using ng2-charts

How can I display data on a pie chart like this? https://i.sstatic.net/WX9ptm.png Like shown in the image below: https://i.sstatic.net/sqlv2m.png <canvas baseChart class="pie" [data]="Data" [labels]="Labels" [colors]="Colors" [chartType]="p ...

Utilizing google.maps.places.Autocomplete within a JHipster application with a modal pop-up feature

I am struggling to make google.maps.places.Autocomplete function properly within a modal in Jhipster 4.6.1 / angular 4.2. The issue lies with the display of results, as the z-index of the .modal seems to be conflicting with the google css, resulting in no ...

Why does Angular routerlink display %20 before the id path?

In my quest to showcase messages from a nested collection of messages, I have encountered a peculiar issue. When clicking on the "view" tag within certain cards, I use routerlink to navigate to the intended path where messages are displayed. Strangely en ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

What steps can I take to safeguard my App API from unauthorized access and misuse?

Is this the right place to ask for help with my app that is split into frontend (Angular) and backend/API (Nodejs)? The API has public endpoints for the frontend, but I want to protect it from being accessed or exploited by unauthorized parties. I consid ...