数字管道0或2个小数位 [英] Number pipe either 0 or 2 decimal places

查看:96
本文介绍了数字管道0或2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现数字格式,以便如果数字是舍入的,则不应有小数位占位符.00,否则应使用2个位,并且仅使用2个小数位.例如:

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

根据文档,您只能指定小数位数的范围(例如|number:'.0-2'),而不能指定特定的选择(例如|number:'.0,2');我是对的还是有办法吗?

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?

我知道我可以用一些*ngIf -s达到相同的效果,但是如果可能的话,我想避免.

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

推荐答案

如果您想对变量做一件事以上,则最佳实践是创建两个不同的管道并将它们一起使用.重要的是从左到右的顺序.如果您只想显示两位数,则可以使用诸如deicmalPipe之类的内置管道:

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 或只是检查该主题: 堆栈溢出答案

Angular Doc Or just check that topic: Stack overflow answer

如果要显示1而不是1.00,则可以创建自定义管道,在该管道中检查字符是否为00或其他.如果是00,则返回不包含这些数字的数字.

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.

这篇关于数字管道0或2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆