typescript 在离子输入中强制 2 个小数位精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42069234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force 2 decimal places precision in ion-input
提问by kosiara - Bartosz Kosarzycki
I'd like to always display numbers with two decimal places precisionin ion-input. So that:
我想始终在ion-input 中以两位小数精度显示数字。以便:
1.01
1.10
1.20
1.23
are NOTdisplayed as: 1.1 and 1.2, but appear as 1.10 and 1.20
不显示为:1.1 和 1.2,但显示为 1.10 和 1.20
My model is:
我的模型是:
export class HomePage {
public myValue:number;
}
with the html file as follows:
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>
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)
它适用于网络浏览器(MacOS,55.0.2883.95(64 位)),但不适用于 Android(在 7.1 上测试)
Any suggestions?
有什么建议?
回答by Christopher Moore
Store the number as inputted, and format using the decimal pipewhen outputting the value. This will always display 2dp
存储输入的数字,并在输出值时使用十进制管道进行格式化。这将始终显示 2dp
{{ myValue | number:'1.2-2' }}
{{ 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
注意:您需要将其设置为provider
上app.module.ts
app.module.ts
app.module.ts
import { DecimalPipe } from '@angular/common';
providers: [
DecimalPipe
]
回答by Parag Ghadge
**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