Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 show two decimals in input

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.

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)

like image 799
Faabass Avatar asked Nov 13 '17 13:11

Faabass


People also ask

How do you display upto 2 decimal places?

printf("%. 2f", value);

Can there be 2 decimals in a number?

They have two digits after the decimal point − or we say they have two decimal digits. We can also illustrate hundredths by dividing a square into a hundred parts. 32 hundredths. This is twenty hundredths.


1 Answers

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

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

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"/>
    
like image 50
JuanDM Avatar answered Oct 20 '22 13:10

JuanDM