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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55184945/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:48:55  来源:igfitidea点击:

Adding Two Decimal Place to Number TypeScript Angular

angulartypescriptdecimal

提问by David La Grange

Cant seem to figure this out. I have tried many different variations. This is on an Angular project.

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

I want a percent number to always be shown with two decimal places even if the user only types a whole number.

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

I cant switch the data type around as a lot of other code has been written around it being a number.

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

The problem is that TypeScript does not allow var and I am having trouble getting to add the extra zeros or round said number to two decimals. It always seems to strip them.

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

Declaration:

宣言:

 percent: number;

Some things I have tried.

我尝试过的一些事情。

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:

HTML:

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

I have also tried piping on front end but have problems with that as well.

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

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

Thanks for your tips and help!

感谢您的提示和帮助!

回答by Steve Land

Treating it as a number and formatting in the view is the correct approach.

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

However, you're mixing up binding & formatting, for example: [(ngModel)]="{{percent | number : '1.2-2'}}"is (very roughly!) equivalent to saying in english: bind my model to the string interpolation of...my model.

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

Try:

尝试:

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

There are good examples of number pipe usage in the docs: https://angular.io/api/common/DecimalPipe#example

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

回答by Richard

You've done all the work, but just haven't put the right bits together. Parsing the float works, and toFixed(2)was correctly returning a string with 2 decimal places, you just need to use them together:

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

parseFloat(input).toFixed(2)

parseFloat(input).toFixed(2)