我有一个angular2应用,经过一些计算后,需要在输入中始终显示两位小数。但是,尽管我在组件中强制使用两位小数,但在输入中它以零小数,一个小数或该数字具有的小数来显示它,但我需要始终显示两个。

在 Controller 中,我以这种方式强制使用两个小数

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

但是当我证明时,结果可以具有不同的小数位数
<input name="number" pattern="^[0-9]+(\.[0-9]{1,2})?" step="0.01" formControlName="number" type="button" class="form-control" id="number" >

加上I; m使用TypeScript,字段类型是数字(我认为这会导致四舍五入)

最佳答案

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

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

要使用该软件包:

  • 安装软件包
    npm i angular2-text-mask text-mask-addons --save
  • 将其导入您的应用程序模块文件中
    import { TextMaskModule } from 'angular2-text-mask';
    
    @NgModule({
      imports: [
        /* ... */
        TextMaskModule
      ]
      /* ... */
    })
    export class AppModule { }
    
  • 在您的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
      });
    
    }
    
  • 在您的component.html中
    <input type="text" [textMask]="{mask: currencyMask}" name="receivedName" id="received" class="form-control" maxlength="50" [(ngModel)]="price"/>
    
  • 10-07 19:20
    查看更多