Angular2 show two decimal places in input

I have an angular2 application which should ALWAYS show two decimal places on inputs after some calculations. But although I force two decimal places in the component, at the input it shows it with zero depinimal, one decimal or decimal number, which has a number, but what I need is to always show two.

In the controller, I force to have two decimal places this way

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

But when I show that the result may have a different decimal size

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

Addition of this I; m using TypeScript and the type of the field is a number (which I think causes rounded)

+5
source share
8 answers

In the end, I did not find the right answer ...

I did 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 call this function in ngOnInit, so I always show the decimal number for the user. The only thing to do is that if the user changes the value and removes the decimal numbers, the number will not be filled with the corresponding 00.

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

0
source

I would suggest you use a mask in the input field, there is a text-mask package that I used before and it works!

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

To use the package:

  • Install package

    npm i angular2-text-mask --save

  • Import it into your module application file

    import { TextMaskModule } from 'angular2-text-mask';

  • In component.ts file

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

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

TL; dg; Option 1: return a string, do not convert to a number. Option 2: use the number tube.

toFixed returns a string.

You convert the result toFixed to a number

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

When you convert "1.20" to a number, it โ€œremovesโ€ the extra 0 returning 1.2 .

To show the result with two decimal places, you can return the result as a string so that 0 not cropped or used the channel.

You can use the number number

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

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

  • minIntegerDigits - the minimum number of integer digits. The default is 1.
  • minFractionDigits is the minimum number of digits after a fraction. The default is 0.
  • maxFractionDigits - the maximum number of digits after the fraction. Default is 3.

With the pipe, you can save the code that returns the number, and it will only change how this value is formatted when you display it on the screen.

+3
source

In angular 2 DecimalPipe, this will be useful for your requirement. Please use it. Example:

 Use format '3.2-5' : minIntegerDigits = 3 minFractionDigits = 2 maxFractionDigits = 5 num = 12.324324 {{num1 | number:'3.2-5'}} 012.63847 
0
source

I donโ€™t know if I understood the problem correctly, but I realized that you somehow want to force the input to contain two digits after the decimal. Here is an attempt: You need to convert the number to a float type and, as you want it to be attached to two decimal points, use the toFixed method.

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

Hope this helps.

0
source

If your input is inside a form named: inputForm, for example,

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

 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 can get some log-erros, but I think this is not very important for this workaround

0
source

Use this tube

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

0
source

Decimalpipe

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

 number_expression | number[:digitInfo] 

Finally, we get the decimal number as text. Find a description. number_expression: an angular expression that will return a number. number: The pipe keyword that is used with the pipe operator. digitInfo: defines the format of the number.

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

 {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} 

Find a 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. 
0
source

Source: https://habr.com/ru/post/1273323/


All Articles