将两个小数位添加到数字 TypeScript Angular

Dav*_*nge 7 decimal typescript angular

似乎无法弄清楚这一点。我尝试了许多不同的变体。这是在一个 Angular 项目中。

我希望百分比数字始终显示两位小数,即使用户只输入一个整数。

我无法切换数据类型,因为围绕它编写的许多其他代码是一个数字。

问题是 TypeScript 不允许 var 并且我无法添加额外的零或将所述数字四舍五入到两位小数。它似乎总是剥离它们。

宣言:

 percent: number;
Run Code Online (Sandbox Code Playgroud)

我尝试过的一些事情。

1:
this.percent = Math.round(this.percent * 1e2) / 1e2;

2:
this.percent = this.percent.toFixed(2); // Throws error cant assign string to num because to fixed returns string

3:
const percentString = this.percent.toString() + '.00';
this.percent = parseFloat(percentString) // Strips 00 (Tried this to just add zeros to whole number as test [will be making it more dynamic])

4:
this.percent = Math.round(this.percent * 100) / 100;

5: (This whole function from another SOF)

  addZeroes(num) {
// Convert input string to a number and store as a variable.
    let value = Number(num).toString();
// Split the input string into two arrays containing integers/decimals
    const res = num.split('.');
// If there is no decimal point or only one decimal place found.
    if (res.length === 1 || res[1].length < 3) {
// Set the number to two decimal places
      value = parseFloat(value).toFixed(2);
    }
// Return updated or original number.
    return value;
  }

and then

this.percent = parseFloat(this.addZeroes(this.percent));

6:
this.percent = parseFloat(this.percent).toFixed(2); // Error inside parseFloat: TS2345: Argument of type 'number' is not assignable to parameter of type 'string'

7:
this.percent = parseFloat(this.percent.toString()).toFixed(2); // Throws error on this.percent assignment: TS2322: Type 'string' is not assignable to type 'number'

8:
this.percent = Number(this.percent).toFixed(2); // Error on assignment: TS2322: Type 'string' is not assignable to type 'number'.
Run Code Online (Sandbox Code Playgroud)

HTML:

  <mat-form-field>
    <input
      matInput
      [numbers]="'.'"
      type="text"
      maxlength="5"
      [placeholder]="'Percent'"
      [(ngModel)]="percent"
      (change)="updateDollarAmountNew()"
      numbers
      name="percent">
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

我也试过在前端管道,但也有问题。

[(ngModel)]="p.percent | number : '1.2-2'" // Error: ng: The pipe '' could not be found

[(ngModel)]="{{percent | number : '1.2-2'}}" // Error: unexpected token '}}'

[(ngModel)]={{percent | number : '1.2-2'}} // Error: Attribute number is not allowed here

[(ngModel)]={{percent | number : 2}} // Error: : expected

// And so on...
Run Code Online (Sandbox Code Playgroud)

感谢您的提示和帮助!

Ric*_*ard 9

你已经完成了所有的工作,但只是没有把正确的部分放在一起。解析浮点数有效,并toFixed(2)正确返回一个带有 2 个小数位的字符串,您只需要一起使用它们:

parseFloat(input).toFixed(2)


Ste*_*and 8

在视图中将其视为数字和格式是正确的方法。

但是,您正在混淆绑定和格式,例如: [(ngModel)]="{{percent | number : '1.2-2'}}" is(非常粗略!)相当于用英语说:将我的模型绑定到...我的模型的字符串插值

尝试:

<div>{{percent | number : '1.2-2'}}</div>
Run Code Online (Sandbox Code Playgroud)

文档中有很好的数字管道使用示例:https : //angular.io/api/common/DecimalPipe#example