Angular 2 - How to get rid of extra decimal places in Angular binding?

I have such a statement in my view, and the binding has a meaning that allows you to say 6970.87127381382131831, but I want to limit it to a maximum of two decimal places. Since I am listing elements with ngFor, I could not use the object to restrict it with .toFixed (2). Thank you all!

{{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier }} 

I tried the method below:

  {{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : 2 }} 

Did not help me.

+5
source share
2 answers

The following expression allows you to set the decimal part to two digits:

  {{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : '1.2-2' }} 

1.2-2 means: at least one digit before the decimal point, at least 2 digits after the decimal point, but no more than two digits.


 {{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : '1.0-2' }} 

1.0-2 means: at least one digit before the decimal point and no more than 2 digits after.


About Angular DecimalPipes and configuration: https://angular.io/api/common/DecimalPipe

+3
source

as reported in official docs https://docs.angularjs.org/api/ng/filter/number

 {{ number_expression | number : fractionSize}} 

in your case:

  {{ (cartitem.original_price * cartitem.qty * cartitem.unit_multiplier) | number : 2 }} 

if you want to correct the number of digits, you can create your own filter

 App.filter('twoDecimal',function(input, scope){ return function(){ return input.toFixed(2); } }) 

and apply it

  {{ (cartitem.original_price * cartitem.qty * cartitem.unit_multiplier) | twoDecimal }} 
+1
source

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


All Articles