我已经写了一个接受数字的指令,并且取决于例如它是10,000还是10,000,000,它将返回10k,10M等。我的网站中的一个屏幕需要以小数点后两位显示,而另一个屏幕不显示#39;吨。我当前的实现显示最多2位小数。如何将其扩展为在需要时不显示
import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'shortNumberFormat'
})
export class ShortNumberFormatDirective implements PipeTransform {
constructor() { }
transform(number: any) {
if (number == null || isNaN(number)) {
return;
}
const hasMinus = String(number).charAt(0) === '-' ? true : false;
number = String(number).charAt(0) === '-' ?
+ String(number).substring(1, number.length) : number;
if (number <= 999) { // hundreds
number = number.toFixed(2) ;
} else if (number >= 1000 && number <= 999999) { // thousands
number = (number / 1000).toFixed(2) + 'K';
} else if (number >= 1000000 && number <= 999999999) { // millions
number = (number / 1000000).toFixed(2) + 'M';
} else if (number >= 1000000000 && number <= 999999999999) { // billions
number = (number / 1000000000).toFixed(2) + 'B';
}
if (hasMinus) {
return '-' + number;
} else {
return number;
}
}
}
答案 0 :(得分:5)
根据docs:
管道类实现了PipeTransform接口的转换 接受输入值后跟可选参数和的方法 返回转换后的值。
这允许您在大多数情况下设置默认值为零小数,但可以选择传入2
以获得两位小数。
import {Component, OnInit, Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'shortNumberFormat'
})
export class ShortNumberFormatDirective implements PipeTransform {
transform(number: any, decimals = 0) {
if (number == null) {
return;
}
number = parseFloat(number);
if (isNaN(number)) {
return;
}
const signPrefix = number < 0 ? '-' : '';
number = Math.abs(number);
if (number <= 999) { // hundreds
number = number.toFixed(decimals);
} else if (number >= 1000 && number <= 999999) { // thousands
number = (number / 1000).toFixed(decimals) + 'K';
} else if (number >= 1000000 && number <= 999999999) { // millions
number = (number / 1000000).toFixed(decimals) + 'M';
} else { // billions
number = (number / 1000000000).toFixed(decimals) + 'B';
}
return signPrefix + number;
}
}
答案 1 :(得分:1)
您可以向管道添加参数boolean isRequired ,以判断是否需要应用管道。
transform(number: any, isRequired: boolean) {
if (number == null || isNaN(number)) {
return;
}
if (isRequired) return number;
else {
const hasMinus = String(number).charAt(0) === '-' ? true : false;
number = String(number).charAt(0) === '-' ?
+ String(number).substring(1, number.length) : number;
if (number <= 999) { // hundreds
number = number.toFixed(2) ;
} else if (number >= 1000 && number <= 999999) { // thousands
number = (number / 1000).toFixed(2) + 'K';
} else if (number >= 1000000 && number <= 999999999) { // millions
number = (number / 1000000).toFixed(2) + 'M';
} else if (number >= 1000000000 && number <= 999999999999) { // billions
number = (number / 1000000000).toFixed(2) + 'B';
}
if (hasMinus) {
return '-' + number;
} else {
return number;
}
}
}
然后,当你希望管道不改变这样的格式时,你只需要添加一个参数:{{ 1000000 | shortNumberFormat:true }}