Ensure ion-input values are accurate to two decimal places

Is there a way to ensure that numbers are always displayed with two decimal places precision in ion-input? For example:

1.01
1.10
1.20
1.23

Instead of displaying as 1.1 and 1.2, they should appear as 1.10 and 1.20.

In my model:

export class HomePage {
   public myValue:number;
}

The corresponding html file looks like this:

<ion-content padding>
  <h3>Hello</h3>
  <ion-row margin-right="50px" margin-left="50px">
      <ion-input type="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01"
                 [(ngModel)]="myValue" placeholder="0.00"></ion-input>
  </ion-row>
</ion-content>

I have also attempted using the following simpler code:

<ion-input type="number" step="0.01"
                     [(ngModel)]="myValue" placeholder="0.00"></ion-input>

This solution works on web browsers (MacOS, 55.0.2883.95) but fails on Android devices (tested on version 7.1).

Any ideas to resolve this issue?

Answer №1

To preserve the entered number, apply formatting using the decimal pipe when displaying the value. This will consistently show 2 decimal places.

{{ myValue | number:'1.2-2' }}

If you need to utilize the pipe within the component itself, such as for validation purposes, you can inject it.

import { DecimalPipe } from '@angular/common';
class MyService {

    constructor(private decimalPipe: DecimalPipe) {}

    twoDecimals(number) {
        return this.decimalPipe.transform(number, '1.2-2');
    }
}

Note: Make sure to declare it as a provider in your app.module.ts

app.module.ts

import { DecimalPipe } from '@angular/common';

 providers: [
     DecimalPipe
  ]

Answer №2

                  **HTML : **                
 <ion-input type="number" [(ngModel)]="defaultQuantity" formControlName="defaultQuantity" (ngModelChange)="changeQuantity($event)">


    ***Function : ***
    
    import { ChangeDetectorRef } from '@angular/core';

    export class OrderPage {

    constructor(public cdRef : ChangeDetectorRef ){}

          changeQuantity(value){
                    //trigger manual change detection
                    this.cdRef.detectChanges();
                    if(value.indexOf('.') !== -1)
                    {
                      this.defaultQuantity = value.substr(0, value.indexOf('.')+3);
                    } else {
                      this.defaultQuantity = value.length > 4 ? value.substring(0,4) : value;
                    }
                 }

    }


        **OUTPUT :** 

                1.01
                1.10
                1.20
                1.23

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

Tips for bringing in a class that has been exported from a module

I have a typescript file (generated) that is being used in my angular project. The contents of this file called contracts.ts are as follows: export module A.B.C.Models { export class Activity { prop1: number; ... } } I am attempting to use t ...

What is the best way to receive the result of an asynchronous function as an input and showcase it using express?

I have recently started learning about node and express My goal is to create an API that can fetch data from an external source and use that data for my application Is there a way to retrieve the result of an asynchronous method and display it using the ...

Disabling the Toolbar in iOS Progressive Web Apps (PWAs

Recently, I developed a basic Angular PWA and added it to my iPhone's Homescreen. In order to eliminate the Safari Toolbar, I made sure to include this code in my index.html: <meta name="apple-mobile-web-app-capable" content="yes"> After imple ...

Error message appears when using TypeScript with a React Material table showing a generic type error

I am currently attempting to implement react-material in a Typescript project. As a newcomer to Typescript, I am encountering some errors that I am unsure how to resolve. In this gist, I am trying to create a reusable React component (Please view the gis ...

Angular 9 Alert : TypeError: Unable to access property 'routes' as it is undefined

Currently, I am in the process of learning Angular 9 and experimenting with new features. Recently, I decided to explore router-outlets with a name property which is demonstrated in the code snippet below. This is the template I used: <router-outlet n ...

The parameter value in Angular routes is substituted with the parameter name in the AuthGuard's canLoad method

Within my AuthGuardService, I have a function called canLoad that accepts a parameter of type Route. In this function, I set the authentication redirect URL to the path property of the Route parameter. An issue arises when the path contains a route parame ...

Guide on embedding child components in content using ngx-markdown within Angular version 14

I've been struggling to find a solution to this issue for some time now. We are receiving HTML content from an epi-server that needs to be dynamically rendered in a component. While ngx-markdown works well with standard HTML elements, it seems to ign ...

Tips for changing the theme color in applications such as Angular

Is there a way to dynamically change the theme color within the head tag in angular 4 applications? <meta name="theme-color" content="#db5945"> ...

Simulating NgRx store using a selector in Angular version 10

I am a novice when it comes to creating test cases, however, I have been tasked with writing tests for an Angular 10 app that utilizes ngrx to manage user information. Below is the ngOnInit function: this.store.pipe(select(userInfo)).subscribe((data) => ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

When using Angular 10 or later, the mouseclick event will consistently trigger Angular's change detection mechanism

When I bind an event to elements on a component's HTML page, the component continues to detect changes even when the element event is fired. Despite setting the change detection mode of the component to OnPush, this behavior persists. To test this, I ...

Checking for duplicate entries in an array created with the Angular form builder

I am currently utilizing angular6 reactive form with form builder and form array. The issue I am encountering is duplicate subject entries from the drop down in the form array. How can I implement validation to prevent duplicate entries in the form array? ...

multer failing to upload files using the default example

I am encountering difficulties with getting my code to function properly and I am not receiving any errors from multer. I have thoroughly double-checked everywhere for potential mistakes, but I am still stuck. Any assistance would be greatly appreciated. ...

Encountering a problem while attempting to integrate a modal using ng2-bootstrap

I encountered an issue while trying to incorporate a modal using ng2-bootstrap. The error message displayed was 'Error: ApplicationRef instance not found', and I am unsure of how to resolve it. After researching, I found that for ng2-bootstrap, ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

Executing the command `subprocess.run("npx prettier --write test.ts", shell=True)` fails to work, however, the same command runs successfully when entered directly into the terminal

Here is the structure of my files: test.py test.ts I am currently trying to format the TypeScript file using a Python script, specifically running it in Command Prompt on Windows. When I execute my python script with subprocess.run("npx prettier --w ...

"Troubleshooting the issue of Angular's ng-selected not functioning properly within an edit

https://i.stack.imgur.com/ZpCmx.png https://i.stack.imgur.com/h3TA6.png TS Pincodes: Array<string> = []; Html <ng-select [items]="Pincodes" [searchable]="true" [multiple]="true" [(ngModel)]="updateZoneDetails ...

The Observable pipeline is typically void until it undergoes a series of refreshing actions

The issue with the observable$ | async; else loading; let x condition usually leads to staying in the loading state, and it requires multiple refreshes in the browser for the data to become visible. Below is the code snippet that I utilized: // TypeScript ...

Instructions on how to extract and display the key-value pairs from a nested JSON array in Angular 2, then populate them in a select box

My goal is to extract data from a Json data model and populate a select box with the data as drop-down items. However, I am encountering difficulties in achieving this as the entire Json array is being printed instead of just the 3 major headings that I wa ...

Type of condition based on function parameter values

I am facing a challenge where I need to merge two separate Typescript methods into one with the same name getDevice. The first method only requires a number input to return a Device, or null if no device is found: protected getDevice(deviceId: number): Dev ...