【问题标题】:Force 2 decimal places precision in ion-input强制离子输入精确到小数点后 2 位
【发布时间】:2017-06-23 11:31:41
【问题描述】:

我希望在 ion-input 中始终显示具有两位小数精度的数字。所以:

1.01
1.10
1.20
1.23

显示为:1.1 和 1.2,但显示为 1.10 和 1.20

我的模型是:

export class HomePage {
   public myValue:number;
}

用html文件如下:

<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>

我也简单地尝试过:

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

它可以在网络浏览器(MacOS,55.0.2883.95(64 位))上运行,但不能在 Android 上运行(在 7.1 上测试)

有什么建议吗?

【问题讨论】:

  • 嗨,我想要和你一样的例子,我使用的是 ionic 最新版本 3.9.2 和 typescript 版本 2.3.4

标签: angular typescript ionic-framework ionic2 ionic3


【解决方案1】:

存储输入的数字,并在输出值时使用decimal pipe 格式化。这将始终显示 2dp

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

如果你想在组件本身中使用管道,也许作为验证逻辑的一部分,你可以注入它。

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

    constructor(private decimalPipe: DecimalPipe) {}

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

注意:您需要在app.module.ts上将其设置为provider

app.module.ts

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

 providers: [
     DecimalPipe
  ]

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多