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

时间:2019-03-15 14:34:07

标签: angular typescript decimal

似乎无法解决这个问题。我尝试了许多不同的变化。这是在Angular项目中。

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

我无法切换数据类型,因为很多其他代码已经写成数字了。

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

声明:

 percent: number;

我尝试过的一些东西。

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

HTML:

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

我也尝试过在前端进行管道传输,但是也有问题。

[(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...

感谢您的提示和帮助!

2 个答案:

答案 0 :(得分:1)

您已经完成了所有工作,但还没有将正确的内容放在一起。解析float的工作原理,并且toFixed(2)正确返回了一个2位小数的字符串,您只需要一起使用它们:

parseFloat(input).toFixed(2)

答案 1 :(得分:1)

将其作为数字进行处理并在视图中进行格式化是正确的方法。

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

尝试:

<div>{{percent | number : '1.2-2'}}</div>

文档中有一些很好的号码管道用法示例:https://angular.io/api/common/DecimalPipe#example