typescript Angular2 在输入中显示两位小数

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

Angular2 show two decimals in input

javascriptangulartypescript

提问by Faabass

I have an angular2 app that needs to show ALWAYS two decimals in inputs after some calculations. But although in the component I force to have two decimals, in the input it shows it with zero decinmal, one decimal or the decimals that the number has but what I need is to show always two.

我有一个 angular2 应用程序,在进行一些计算后,它需要在输入中始终显示两位小数。但是,尽管在组件中我强制使用两位小数,但在输入中它以零十进制、一位小数或数字所具有的小数显示它,但我需要的是始终显示两位。

In the controller I force to have two decimals in this way

在控制器中,我强制以这种方式保留两位小数

return +(this.getCost() * this.getQuantity()).toFixed(2);

But when I show that, the result can have different decimals size

但是当我证明这一点时,结果可以有不同的小数大小

<input name="number" pattern="^[0-9]+(\.[0-9]{1,2})?" step="0.01" formControlName="number" type="button" class="form-control" id="number" >

Adding that I;m using TypeScript and the field type is number (which I think is causing the rounded)

补充说我正在使用 TypeScript 并且字段类型是数字(我认为这是导致四舍五入的)

采纳答案by Faabass

At the end I did't find the right answer...

最后我没有找到正确的答案......

What I did was to create the following function

我所做的是创建以下功能

fixDecimals(value : string){
    value = "" + value;
    value = value.trim();
    value = parseFloat(value).toFixed(2);
    return value;
  }

And I changed the input type to text (instead of number).

我将输入类型更改为文本(而不是数字)。

And I'm calling this function in the ngOnInit so, I'm always showing the number with to decimals to the user. The only pending thing is that if the user change the value and remove the decimals, the number won't be completed with the corresponding 00.

我在 ngOnInit 中调用这个函数,所以我总是向用户显示带小数的数字。唯一悬而未决的是,如果用户更改值并删除小数,则数字将不会以相应的 00 完成。

I tried with the onChange, but the prompt goes to the end of the input (which is very awkard for the user)

我尝试使用 onChange,但提示转到输入的末尾(这对用户来说非常尴尬)

回答by JuanDM

I would suggest you to use a mask on the input field there is a package text-maskthat i've used before and works!

我建议您在输入字段上使用掩码,我以前使用过一个包text-mask并且可以使用!

Note: take a look at you html input type, you said that is number, but actually in your question the type is button

注意:看看你的html输入类型,你说的是数字,但实际上在你的问题中类型是按钮

To use the package:

要使用该包:

  1. Install the packages

    npm i angular2-text-mask text-mask-addons --save

  2. Import it in you app-module file

    import { TextMaskModule } from 'angular2-text-mask';
    
    @NgModule({
      imports: [
        /* ... */
        TextMaskModule
      ]
      /* ... */
    })
    export class AppModule { }
    
  3. In you component.ts

    import createNumberMask from 'text-mask-addons/dist/createNumberMask';
    
    @Component({   
      selector: 'app-my-component',   
      templateUrl: './my-component.html',   
      styleUrls: ['./my.component.scss'] }) 
    
      export class MyComponent implements OnInit { 
      public price = 0;
    
      private currencyMask = createNumberMask({
        prefix: '',
        suffix: '',
        includeThousandsSeparator: true,
        thousandsSeparatorSymbol: ',',
        allowDecimal: true,
        decimalSymbol: '.',
        decimalLimit: 2,
        integerLimit: null,
        requireDecimal: false,
        allowNegative: false,
        allowLeadingZeroes: false
      });
    
    }
    
  4. In your component.html

    <input type="text" [textMask]="{mask: currencyMask}" name="receivedName" id="received" class="form-control" maxlength="50" [(ngModel)]="price"/>
    
  1. 安装软件包

    npm i angular2-text-mask text-mask-addons --save

  2. 将其导入您的应用程序模块文件

    import { TextMaskModule } from 'angular2-text-mask';
    
    @NgModule({
      imports: [
        /* ... */
        TextMaskModule
      ]
      /* ... */
    })
    export class AppModule { }
    
  3. 在你的 component.ts

    import createNumberMask from 'text-mask-addons/dist/createNumberMask';
    
    @Component({   
      selector: 'app-my-component',   
      templateUrl: './my-component.html',   
      styleUrls: ['./my.component.scss'] }) 
    
      export class MyComponent implements OnInit { 
      public price = 0;
    
      private currencyMask = createNumberMask({
        prefix: '',
        suffix: '',
        includeThousandsSeparator: true,
        thousandsSeparatorSymbol: ',',
        allowDecimal: true,
        decimalSymbol: '.',
        decimalLimit: 2,
        integerLimit: null,
        requireDecimal: false,
        allowNegative: false,
        allowLeadingZeroes: false
      });
    
    }
    
  4. 在你的 component.html

    <input type="text" [textMask]="{mask: currencyMask}" name="receivedName" id="received" class="form-control" maxlength="50" [(ngModel)]="price"/>
    

回答by BrunoLM

tl;dr; Option 1: return a string, don't convert to number. Option 2: Use a number pipe.

tl;博士; 选项1:返回一个字符串,不要转换为数字。选项 2:使用数字管道。

toFixedreturns a string.

toFixed返回一个字符串。

You are converting the result of toFixedto a number

您正在将结果转换toFixed为数字

return +(this.getCost() * this.getQuantity()).toFixed(2);
       ↑

When you convert "1.20"to a number it will "remove" the extra 0returning 1.2.

当您转换"1.20"为数字时,它将“删除”额外的0返回1.2.

To show the result with 2 decimals you can return the result as a string so the 0doesn't get cut off, or use a pipe.

要显示 2 位小数的结果,您可以将结果作为字符串返回,这样0就不会被截断,或者使用管道。

You can use the number pipe

您可以使用数字管道

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

Format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

格式: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

  • minIntegerDigitsis the minimum number of integer digits to use. Defaults to 1.
  • minFractionDigitsis the minimum number of digits after fraction. Defaults to 0.
  • maxFractionDigitsis the maximum number of digits after fraction. Defaults to 3.
  • minIntegerDigits是要使用的最小整数位数。默认为 1。
  • minFractionDigits是分数后的最小位数。默认为 0。
  • maxFractionDigits是分数后的最大位数。默认为 3。

With the pipe you can keep your code returning a number and it will only change how the value is formatted when you show it on the screen.

使用管道,您可以让代码返回一个数字,并且只会在您在屏幕上显示该值时更改该值的格式。

回答by MKant

I don't know if I understood the problem correctly but what I understood is you somehow want to force the input to contain two digits after decimal. Here is a try: You need to convert the number to a float type and as you want it to be fixed to two decimal points use toFixed method.

我不知道我是否正确理解了这个问题,但我的理解是你想以某种方式强制输入包含小数点后的两位数。这是一个尝试:您需要将数字转换为浮点类型,并且您希望将其固定为两个小数点,请使用 toFixed 方法。

Number.parseFloat(x).toFixed(2)
//Where x is the number which needs to be converted to a float type.

I hope this helps.

我希望这有帮助。

回答by Kostas Asargiotakis

If your input is inside a form with name: inputForm e.g

如果您的输入在名称为 inputForm 的表单中,例如

HTML

HTML

    <form [formGroup]="inputForm">
      <input name="number" (keyup)="fixNumber()" pattern="^[0-9]+(\.[0-9]{1,2})?" step="0.01" `enter code here`formControlName="number" type="button" class="form-control" id="number">
</form>

TS

TS

public fixNumber(){

      let value =this.inputForm.get('number').value;
      let prefix:string = value.toString().split('.')[0];
      let suffix:string = value.toString().split('.')[1];
      if(suffix.length > 2){
        let suffix_subed = suffix.substr(0,2);
        let new_value = prefix+'.'+suffix_subed;
        this.inputForm.get('number').setValue(new_value);
      }
}

You may get some log erros, but i think that's not big dead for that workaround

您可能会收到一些日志错误,但我认为这对于该解决方法来说并不是什么大问题

回答by Sathiyaraj

In angular 2 have DecimalPipethis will helpful to your requirement.Please Use it. Sample:

在 angular 2 中有DecimalPipe这将有助于您的要求。请使用它。样本:

Use format '3.2-5' : 

minIntegerDigits = 3 
minFractionDigits = 2 
maxFractionDigits = 5 

num = 12.324324

{{num1 | number:'3.2-5'}} 

012.63847 

回答by Ali Shawky

Use This Pipe

使用这个管道

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

{{ 数字 | 数字:'1.2-2'}}

回答by Ali Shawky

DecimalPipe

十进制管道

DecimalPipe is an angular Pipe API and belongs to CommonModule. DecimalPipe is used to format a number as decimal number according to locale rules. It uses number keyword with pipe operator. Find the syntax.

DecimalPipe 是一个 angular Pipe API,属于 CommonModule。DecimalPipe 用于根据区域设置规则将数字格式化为十进制数。它使用带有管道运算符的数字关键字。找到语法。

number_expression | number[:digitInfo]

Finally we get a decimal number as text. Find the description. number_expression: An angular expression that will give output a number. number : A pipe keyword that is used with pipe operator. digitInfo : It defines number format.

最后我们得到一个十进制数作为文本。找到说明。number_expression:一个角度表达式,将给输出一个数字。number :与管道运算符一起使用的管道关键字。digitInfo :它定义了数字格式。

Now we will understand how to use digitInfo. The syntax for digitInfo is as follows.

现在我们将了解如何使用 digitInfo。digitInfo 的语法如下。

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Find the description.

找到说明。

minIntegerDigits : Minimum number of integer digits. Default is 1. 
minFractionDigits : Minimum number of fraction digits. Default is 0. 
maxFractionDigits : Maximum number of fraction digits. Default is 3.