Number pipe either 0 or 2 decimal places

北城以北 提交于 2019-12-21 21:25:09

问题


I'd like to achieve number formatting such that if the number is round there should be no decimal placeholders .00 and otherwise use 2 and only 2 decimal places. For example:

1.23    -> 1.23
1.23456 -> 1.24
1.2     -> 1.20
1.0     -> 1
1       -> 1

According to the docs, you can only specify range of decimal places (e.g. |number:'.0-2') and not specific choice (e.g. |number:'.0,2'); am i right or is there a way?

I'm aware I could achieve the same with some *ngIf-s but would like to avoid if possible.


回答1:


If you want to do more than one thing on your variable, the best practise is to create two diffrent pipes and use them together. Important is order from left to right. If you want to display only two digits you can use built-in pipes like deicmalPipe:

Angular Doc Or just check that topic: Stack overflow answer

If you want to display 1 not 1.00 you can create your custom pipe where it check if that characters are 00 or sth else. If it is 00 it return number without these digits.




回答2:


For displaying 1 instead of 1.0 you can try this.

{{x | number:'1.0-0'}}



回答3:


use :

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

https://angular.io/api/common/DecimalPipe



来源:https://stackoverflow.com/questions/46888351/number-pipe-either-0-or-2-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!