Force 2 decimal places precision in ion-input

18,165

Solution 1

Store the number as inputted, and format using the decimal pipe when outputting the value. This will always display 2dp

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

If you want to use the pipe within the component itself, perhaps as part of the validation logic, 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: You need to set it as a provider on app.module.ts

app.module.ts

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

 providers: [
     DecimalPipe
  ]

Solution 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){
                    //manually launch 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
Share:
18,165
kosiara - Bartosz Kosarzycki
Author by

kosiara - Bartosz Kosarzycki

I'm a senior Java/Android developer constantly developing his skills more here: https://sites.google.com/site/bkosarzyckiaboutme/

Updated on June 28, 2022

Comments

  • kosiara - Bartosz Kosarzycki
    kosiara - Bartosz Kosarzycki almost 2 years

    I'd like to always display numbers with two decimal places precision in ion-input. So that:

    1.01
    1.10
    1.20
    1.23
    

    are NOT displayed as: 1.1 and 1.2, but appear as 1.10 and 1.20

    My model is:

    export class HomePage {
       public myValue:number;
    }
    

    with the html file as follows:

    <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've also tried simply:

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

    It works in the web browser (MacOS, 55.0.2883.95 (64-bit)) but does not work on Android (tested on 7.1)

    Any suggestions?